2014-04-20 53 views
5

我有以下代碼:檢查URL是一個圖像

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)。第二個不是。我怎樣才能做到這一點?

回答

6

您可以爲他們獲取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 
    } 
} 
+0

@Leetmorry thanx的編輯:) – Alladinian

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 
} 
+0

我不知道爲什麼你downvoted,真實的回答,謝謝! – XelharK

+0

這是更好的答案。檢查擴展並不總是可行,例如,返回圖像的cgi可能具有.cgi擴展名,即使它返回的是image/jpeg。 Rags93有一個很好的後續簡化。 –

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; 
} 
+2

還有一個相反的問題。 Dropbox例如具有以文件擴展名結尾的共享鏈接,但是顯示一個html頁面而不是實際的文件。 –

0

到Visputs答案類似,您可以從response.MIMEType獲得Mime類型。

下面的代碼:

- (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

在斯威夫特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") 
} 

注意:此方法適用於指向具有名稱和擴展名的圖像資源的URL,例如:http://www.yourwebapi.com/api/image.jpg, ,但不適用於以下網址:http://www.yourwebapi.com/api/images/12626,因爲在這種情況下,URL字符串不會告訴我們關於mime類型的一切。

如@Visput所示,您應該查看Content-Type HTTP Header並檢查返回的MIME類型。例如,image/jpeg

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]; 

}

相關問題