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

2 回答 2

3

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

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

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

您应该使用 NSURLConnection 下载数据而不阻塞主线程。NSURLRequest从 URL创建一个,将它传递给[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;
}
于 2010-07-24T17:01:08.027 回答
0

进行以下更改:

1.将呼叫更改为

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

目前您正在使用 stringWithContentsOfURL。

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

于 2010-07-24T14:22:04.943 回答