2011-05-15 114 views
7

我有一個for循環,當前循環4次。Objective-C - 檢查URL是否存在

//Add all the URLs from the server to the array 
    for (int i = 1; i <= 5; i++){ 
     NSString *tempString = [[NSString alloc] initWithFormat : @"http://photostiubhart.comoj.com/GalleryImages/%dstiubhart1.jpg", i]; 
     [myURLS addObject: [NSURL URLWithString:tempString]]; 
     [tempString release]; 
    } 

正如你可以看到網址中有一個數字,得到由1每次循環遞增,以創建一個新的URL下一個圖像會。但是,服務器上的圖像數量不一定是4,可能會更多,甚至更少。我的問題是,有沒有一種方法可以檢查URL中是否存儲了圖像?如果沒有,請打破循環並繼續執行程序?

感謝,

傑克

+0

可能[如何檢查一個文件是否存在於特定的URL?](http://stackoverflow.com/questions/2021391/how-to-check-if-a-file-exists-at-particular-url) – zoul 2011-05-15 15:43:10

回答

16

這裏是思想的檢查與HTTP響應

NSURLRequest *request; 
NSURLResponse *response = nil; 
NSError **error=nil; 
NSData *data=[[NSData alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error]]; 
NSString* retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
// you can use retVal , ignore if you don't need. 
NSInteger httpStatus = [((NSHTTPURLResponse *)response) statusCode]; 
NSLog(@"responsecode:%d", httpStatus); 
// there will be various HTTP response code (status) 
// you might concern with 404 
if(httpStatus == 404) 
{ 
    // do your job 
} 

while(httpStatus == 200){ 
    static int increment = 0; 
    increment++; 
    // check other URL yoururl/somthing/increment++ 
} 

但是這將是緩慢的。我的建議是,如果您使用自己的網絡服務器,那麼您可以先發送所有圖像信息。我敢肯定,你在annonymous或其他網站做這個工作:) 讓我知道,如果它可以幫助你或不

-2

這裏是檢查是否網址有效最簡單的方法:

NSURL *URL = [NSURL URLWithString:@"www.your.unvalidated.yet/url"]; 

if ([[UIApplication sharedApplication] canOpenURL:[URL absoluteURL]]) 
{ 
    //your link is ok 
} 
+0

這個不會檢查網址是否有效。我可以把「www.myurlofjustice.com」這樣做,並且這樣做會返回「TRUE」,因爲理論上它仍然會打開一個鏈接。你需要像在'PravatMaskey'的答案中那樣檢查HTTP狀態響應。 – Popeye 2013-12-27 14:36:39

+0

不會。它返回'FALSE'。我現在就測試它! – skywinder 2013-12-27 14:42:20

+0

我剛剛測試了我提供的URL,如果你做了[[UIApplication sharedApplication] openURL:@「www.myurlofjustice」];'它實際上把我帶到谷歌並作爲搜索參數輸入。那麼你如何處理這個問題呢? – Popeye 2013-12-27 14:47:05