检查NSURL是否返回404 [英] Check if NSURL returns 404

查看:148
本文介绍了检查NSURL是否返回404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个URL(由NSURL表示)是否可用或返回404.实现该目标的最佳方法是什么?

I need to check whether a URL (represented by a NSURL) is available or returns 404. What is the best way to achieve that?

我希望如果可能的话,在没有代表的情况下检查此方法。我需要阻止程序执行,直到我知道URL是否可以访问。

I would prefer a way to check this without a delegate, if possible. I need to block the program execution until I know if the URL is reachable or not.

推荐答案

正如您可能已经知道的那样一般错误可以通过didFailWithError方法捕获:

As you may know already that general error can capture by didFailWithError method:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}

但是对于404未找到或500内部服务器错误应该能够捕获didReceiveResponse方法:

but for 404 "Not Found" or 500 "Internal Server Error" should able to capture inside didReceiveResponse method:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if ([response respondsToSelector:@selector(statusCode)])
    {
        int statusCode = [((NSHTTPURLResponse *)response) statusCode];
        if (statusCode == 404)
        {
            [connection cancel];  // stop connecting; no more delegate messages
            NSLog(@"didReceiveResponse statusCode with %i", statusCode);
        }
    }
}

这篇关于检查NSURL是否返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆