检查网址是否为图片

use*_*384 8 objective-c ios

我有以下代码:

NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray* matches = [detector matchesInString:[[imagesArray valueForKey:@"content"] objectAtIndex:indexPath.row] options:0 range:NSMakeRange(0, [[[imagesArray valueForKey:@"content"] objectAtIndex:indexPath.row] length])];
Run Code Online (Sandbox Code Playgroud)

这导致日志:

<NSLinkCheckingResult: 0xa632220>{235, 75}{http://URL/wordpress/wp-content/uploads/2014/04/Digital-Board-2.png}
<NSLinkCheckingResult: 0xa64eb90>{280, 25}{http://www.w3schools.com/}
Run Code Online (Sandbox Code Playgroud)

我需要的是检查它们包含图像的链接.在这种情况下,第一个链接包含图像(PNG).第二个没有.我怎样才能做到这一点?

All*_*ian 7

您可以NSURL为他们获取s并将扩展名与图像扩展名列表进行比较.也许这样的东西:

// A list of extensions to check against 
NSArray *imageExtensions = @[@"png", @"jpg", @"gif"]; //...

// Iterate & match the URL objects from your checking results
for (NSTextCheckingResult *result in matches) {
    NSURL *url = [result URL];
    NSString *extension = [url pathExtension];
    if ([imageExtensions containsObject:extension]) {
        NSLog(@"Image URL: %@", url);
        // Do something with it
    }
}
Run Code Online (Sandbox Code Playgroud)


Vla*_*pko 5

根据此答案,您可以使用HTTP HEAD请求并检查内容类型.
图像的可能内容类型列表在这里.

代码示例:

- (void)executeHeadRequest:(NSURL *)url {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"HEAD"];
    [NSURLConnection connectionWithRequest:request delegate:self]
}

// Delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)response;
    NSString *contentType = [response.allHeaderFields valueForKey:@"Content-Type"];
    // Check content type here
}
Run Code Online (Sandbox Code Playgroud)


Dom*_*ico 5

在Swift 3中,扩展名为:

extension String {

    public func isImage() -> Bool {
        // Add here your image formats.
        let imageFormats = ["jpg", "jpeg", "png", "gif"]

        if let ext = self.getExtension() {
            return imageFormats.contains(ext)           
        }

        return false
    }

    public func getExtension() -> String? {
       let ext = (self as NSString).pathExtension

       if ext.isEmpty {
           return nil
       }

       return ext
    }

    public func isURL() -> Bool {
       return URL(string: self) != nil
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在你viewController(或你想要的任何地方):

 let str = "string"

 // Check if the given string is an URL and an image 
 if str.isURL() && str.isImage() {
     print("image and url")
 }
Run Code Online (Sandbox Code Playgroud)

注意:此方法适用于指向具有名称和扩展名的图像资源的URL,例如: http: //www.yourwebapi.com/api/image.jpg,但它不适用于以下URL: http://www.yourwebapi.com/api/images/12626因为,在这种情况下,URL字符串不会告诉我们关于mime类型的任何信息.

正如@Visput所建议的那样,您应该查看Content-Type HTTP Header并检查返回的mime类型.例如,image/jpeg