Skip to content

Instantly share code, notes, and snippets.

@GE-N
Last active November 11, 2016 07:51
Show Gist options
  • Save GE-N/665fcccfef99c2b49c005a7f0daff373 to your computer and use it in GitHub Desktop.
Save GE-N/665fcccfef99c2b49c005a7f0daff373 to your computer and use it in GitHub Desktop.
import MobileCoreServices
extension String {
func isImageExtension(_ ext: String) -> Bool {
let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext, nil)
guard let imageUTI = uti?.takeRetainedValue() else { return false }
return UTTypeConformsTo(imageUTI, kUTTypeImage)
}
func isImageLink() -> Bool {
guard let url = NSURL(string: self) else { return false }
if isImageExtension((self as NSString).pathExtension) { return true }
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "HEAD"
let session = NSURLSession.sharedSession()
let result = session.synchronousDataTaskWithRequest(result)
guard let response = result.1 as? NSHTTPURLRequest else { return false }
let contentType = response.allHeaderFields["Content-Type"] as? String
return contentType?.containsString("image") ?? false
return false
}
}
public extension NSURLSession {
func synchronousDataTaskWithRequest(request: NSURLRequest) -> (NSData?, NSURLResponse?, NSError?) {
var data: NSData?
var response: NSURLResponse?
var error: NSError?
let semaphore = dispatch_semaphore_create(0)
dataTaskWithRequest(request) {
data = $0
response = $1
error = $2
dispatch_semaphore_signal(semaphore)
}.resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return (data, response, error)
}
}
"http://www.my-image.com/1.jpg".isImageLink() // true
"http://www.my-image.com/2.jpeg".isImageLink() // true
"http://www.my-image.com/3.png".isImageLink() // true
"http://www.my-image.com/4.tff".isImageLink() // true
"http://graph.facebook.com/67563683055/picture".isImageLink() // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment