我有以下代码:
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])];
这个结果在日志中:
<NSLinkCheckingResult: 0xa632220>{235, 75}{http://URL/wordpress/wp-content/uploads/2014/04/Digital-Board-2.png}
<NSLinkCheckingResult: 0xa64eb90>{280, 25}{http://www.w3schools.com/}
我需要的是检查它们包含图像的链接。在这种情况下,第一个链接包含图像(PNG)。第二个没有。我怎么能这样做?
答案 0 :(得分:7)
您可以为他们获取NSURL
,并将扩展名与图片扩展名列表进行比较。也许是这样的事情:
// 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
}
}
答案 1 :(得分:5)
根据此answer,您可以使用HTTP HEAD请求并检查内容类型 图像的可能内容类型列表为here。
代码示例:
- (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
}
答案 2 :(得分: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
}
}
然后在viewController
(或您想要的任何地方):
let str = "string"
// Check if the given string is an URL and an image
if str.isURL() && str.isImage() {
print("image and url")
}
注意 :此方法适用于指向具有名称和扩展名的图像资源的网址,例如:http://www.yourwebapi.com/api/image.jpg, 但它对于这样的网址不起作用:http://www.yourwebapi.com/api/images/12626因为在这种情况下,URL字符串并不能告诉我们关于mime类型的任何信息。
根据@Visput的建议,您应该查看Content-Type HTTP Header并检查返回的mime-type。例如,image/jpeg
答案 3 :(得分:0)
当然,问题在于检查链接而不查看它们背后的资源是因为动态Web服务无法返回图像,但在网址上没有典型的图像扩展名。
您可能采取的另一种方法是尝试仅加载HTTP标头并检查返回的MIME类型。你可以做这个作为后台任务;只需加载标题字段,即可最大限度地减少流量。
这是您可能想要异步执行的同步版本。只是为了证明这个想法:
#import <Foundation/Foundation.h>
BOOL urlIsImage(NSURL *url)
{
NSMutableURLRequest *request = [[NSURLRequest requestWithURL:url] mutableCopy];
NSURLResponse *response = nil;
NSError *error = nil;
[request setValue:@"HEAD" forKey:@"HTTPMethod"];
[NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSString *mimeType = [response MIMEType];
NSRange range = [mimeType rangeOfString:@"image"];
return (range.location != NSNotFound);
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSArray *urlStrings = @[@"http://lorempixel.com/400/200/",
@"http://stackoverflow.com"];
for( NSString *urlString in urlStrings ) {
NSURL *url = [NSURL URLWithString:urlString];
if( urlIsImage(url) ) {
NSLog(@"%@ loads an image",urlString);
}
else {
NSLog(@"%@ does *not* load an image",urlString);
}
}
}
return 0;
}
答案 4 :(得分:0)
与Visputs答案类似,您可以从response.MIMEType
获取MimeType。
这里是代码:
- (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 {
NSLog(@"MIME: %@", response.MIMEType);
// Check content type here
}
答案 5 :(得分:0)
由于NSURLConnection
已被弃用。
获取contentType的类似代码
- (void)executeHeadRequest:(NSURL *)url {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"HEAD"];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSString *contentType = [httpResponse.allHeaderFields valueForKey:@"Content-Type"];
if ([contentType contains:@"image"]) {
NSLog(@"Url is image type");
}
}
[session invalidateAndCancel];
}] resume];
}