2015-10-21 64 views
0

在IOS中是否有任何資源有效的方式(不與主線程綁定)來檢查遠程文件的存在?IOS:檢查遠程文件是否存在

我有存儲在服務器上的用戶圖像。雖然有一個一致的url方案,一些圖像是.jpg,其他的是.gif等,所以爲了得到正確的圖像名稱,我需要檢查user/file.gif是否存在,user/file.jpg是否存在等爲了將文件下載到IOS應用程序。

我發現這個代碼在另一個answer in IOS

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]]; 
     [request setHTTPMethod:@"HEAD"]; 
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

但我不知道如何使用它。理想情況下,我想得到一個布爾型的是或否,以確定.gif文件是否存在,.jpg文件是否存在於用戶配置文件圖片中,以便我可以填寫正確的名稱以下載用戶圖片。

另一種方法是在後端編寫一個服務來返回文件,但是想知道它是否都可以在IOS中完成。

感謝您的任何建議。

回答

3
**Use this function below to check whether file exists at specified url** 

+(void)checkWhetherFileExistsIn:(NSURL *)fileUrl Completion:(void (^)(BOOL success, NSString *fileSize))completion 
{ 
    //MAKING A HEAD REQUEST 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileUrl]; 
    request.HTTPMethod = @"HEAD"; 
    request.timeoutInterval = 3; 

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) 
    { 
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; 
     if (connectionError == nil) { 
      if ((long)[httpResponse statusCode] == 200) 
      { 
       //FILE EXISTS 

       NSDictionary *dic = httpResponse.allHeaderFields; 
       NSLog(@"Response 1 %@",[dic valueForKey:@"Content-Length"]); 
       completion(TRUE,[dic valueForKey:@"Content-Length"]); 
      } 
      else 
      { 
       //FILE DOESNT EXIST 
       NSLog(@"Response 2"); 
       completion(FALSE,@""); 
      } 
     } 
     else 
     { 
      NSLog(@"Response 3"); 
      completion(FALSE,@""); 
     } 

    }]; 
}