开发者

How to check network access to SBJson URL

开发者 https://www.devze.com 2023-04-06 02:30 出处:网络
I\'m using SBJson to retrive data from URL. How to check if I have access to the URL before downloading. I want to check this, sometime application crash if there is no network connection.

I'm using SBJson to retrive data from URL. How to check if I have access to the URL before downloading. I want to check this, sometime application crash if there is no network connection.

Here is my code

id response = [self objectWithUrl:[NSURL URLWithString:@"http://myurl.com/Service.svc/GetId"]];

*I'm using stringWithUrl and objectWithUrl method to download开发者_开发百科 the JSON.


Use the Reachability API and use that URL as your hostname you are testing

http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html

//reachabilityWithHostName- Use to check the reachability of a particular host name. 
+ (Reachability*) reachabilityWithHostName: (NSString*) hostName;


Do NOT use Reachability on the main thread to detect whether you have a network connection. It doesn't work and can lock up for 30 seconds or more, causing your app to be terminated.

Instead you should simply try downloading the data using an NSURLConnection -- this will power up the radio(s) if needed. You will get a callback if an error occurs.

All network connections -including domain name lookups- should be on secondary threads or asynchronous or at least nonblocking. In the case of NSURLs, use NSURLConnection's asynchronous callbacks.

Your application is probably crashing because you are are making a network call from the main thread and locking up for more than 30 seconds, so the system watchdog timer kills you. Looking at your crash logs in Xcode should verify that. Otherwise, you probably just aren't handling the error condition properly.

0

精彩评论

暂无评论...
验证码 换一张
取 消