I'm looking for a way to detect a if an NSURL is a URL to a file format supported by the UIImage class, and if yes, open it in something like MWPhotoBrowser (https://github.com/mwaterfall/MWPhotoBrowser) instead of a UIWebView. My first thought is to have an if condition with all the supported file extensions. I'm wondering if anyone knows of a better way?
You don't know what's at a URL until you at least begin to fetch it. Some URLs look like they end with a filename -- an image filename, even -- but actually point to HTML pages (say, for viewing said image). Some URLs don't appear to end in a filename but do point straight to an image file.
You can get a pretty good hint as to what kind of data is at a URL by making an HTTP HEAD
request: see NSURLRequest
and NSHTTPURLResponse
and look for the Content-Type header. (Those just describe a request and response; you'll need NSURLSession
to perform the request and get a response.)
Even a HEAD request doesn't always report correctly, though: the only way to really be sure if there's an image at a URL is to fetch it -- most image formats are identifiable within the first several bytes of the data, so you can begin a fetch, look at the first partial data you get, and abort the fetch if you don't want the rest.