NSURL 错误处理

发布于 2024-09-10 22:09:04 字数 969 浏览 4 评论 0原文

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

- (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];
}

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];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

树深时见影 2024-09-17 22:09:04

首先,当您调用 stringWithContentsOfURL: 时,您会在等待网络操作完成时阻塞主线程,这是一件坏事,因为如果网络速度缓慢或无法访问,它看起来就像您的应用程序崩溃了。

其次,stringWithContentsOfURL:已被弃用,您应该使用它,即使它仍然阻塞主线程:

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

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

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

- (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;
}

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.

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];

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.

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;
}
人心善变 2024-09-17 22:09:04

进行以下更改:

1. 将调用更改为

    + (id)stringWithContentsOfURL:(NSURL
*)url encoding:(NSStringEncoding)enc error:(NSError **)error

当前您正在使用 stringWithContentsOfURL。

2.处理此调用返回的nil值。如果执行 URL 时出现任何错误,则调用返回 nil 对象。在当前的实现中,您只是添加对象 API 返回(我认为这可能是您崩溃的原因)

Do following changes:

1.Changing the call to

    + (id)stringWithContentsOfURL:(NSURL
*)url encoding:(NSStringEncoding)enc error:(NSError **)error

presently you are using stringWithContentsOfURL.

2.Handle the nil value this call return. if there is any error in executing the URL the call return nil object. in present implementation you are just adding object API return (I think this is might be the reason for your crash)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文