NSURL错误处理 [英] NSURL Error Handling

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

问题描述

我的应用程序应该每隔10秒左右用特定的URL向服务器发出一个请求,更改URL中的某些属性,然后在另一个名为"updateView"的视图中显示该请求,或者显示任何网络错误错误.第一部分工作正常,但如果例如我切换了wifi,应用程序就会崩溃.如何解决此问题以及如何显示各种错误?提前致谢!!这是我的代码(这是每10秒调用一次的方法):

my app is supposed to make a request from a server every 10 seconds or so with a specific url, change some attributes in the url, and then show the request in another view called "updateView" or if any network error occurred display the error. The first part works fine but if i switch of wifi for example the app crashes. How do i fix this and how do i display the various errors? Thanks in advance!! Here's my code (this is the method which gets called every 10 seconds):

- (void)serverUpdate{
CLLocationCoordinate2D newCoords = self.location.coordinate;

gpsUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://odgps.de/chris/navextest?objectid=3&latitude=%2.4fN&longitude=%2.4fE&heading=61.56&velocity=5.21&altitude=%f&message=Eisberg+voraus%21", newCoords.latitude, newCoords.longitude, self.location.altitude]];

self.pageData = [NSString stringWithContentsOfURL:gpsUrl];


[updateView.transmissions insertObject:pageData atIndex:counter];
if (counter == 100) {
    [updateView.transmissions removeAllObjects];
    counter = -1;
}
counter = counter + 1;



    [updateView.tableView reloadData];
self.sendToServerSuccessful = self.sendToServerSuccessful + 1;
[self.tableView reloadData];
}

推荐答案

首先,您在调用stringWithContentsOfURL:时等待主线程等待网络操作完成时阻塞了主线程,这很不好,因为如果网络速度慢或无法访问,看起来您的应用已崩溃.

First, you're blocking the main thread while it waits for the network operation to complete when you call stringWithContentsOfURL: and that's a bad thing because if the network is slow or unreachable, it'll look like your app has crashed.

第二,不推荐使用stringWithContentsOfURL:,即使它仍阻塞主线程,您也应该使用它:

Second, stringWithContentsOfURL: is deprecated and you should use this instead, even though it still blocks the main thread:

self.pageData = [NSString stringWithContentsOfURL:gpsURL encoding:NSUTF8StringEncoding error:nil];

您应该使用NSURLConnection下载数据而不会阻塞主线程.从URL创建NSURLRequest,并将其传递给[NSURLConnection connectionWithRequest:request delegate:self];,这将启动URL连接.

You should be using NSURLConnection to download the data without blocking the main thread. Create a NSURLRequest from the URL, pass it to [NSURLConnection connectionWithRequest:request delegate:self]; which starts the URL connection.

以下是NSURLConnection委托的一些代码:

Here's some code for the NSURLConnection delegate:

- (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)response {
    if ([response isKindOfClass: [NSHTTPURLResponse class]]) {
        statusCode = [(NSHTTPURLResponse*) response statusCode];
        /* HTTP Status Codes
            200 OK
            400 Bad Request
            401 Unauthorized (bad username or password)
            403 Forbidden
            404 Not Found
            502 Bad Gateway
            503 Service Unavailable
         */
    }
    self.receivedData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)aConnection didReceiveData:(NSData *)data {
    [self.receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {
    // Parse the received data
    [self parseReceivedData:receivedData];
    self.receivedData = nil;
}   

- (void)connection:(NSURLConnection *)aConnection didFailWithError:(NSError *)error {
    statusCode = 0; // Status code is not valid with this kind of error, which is typically a timeout or no network error.
    self.receivedData = nil;
}

这篇关于NSURL错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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