0

私のアプリは、特定のURLを使用して10秒ごとにサーバーからリクエストを作成し、URLの一部の属性を変更してから、「updateView」という別のビューにリクエストを表示するか、ネットワークエラーが発生した場合はエラーを表示することになっています。最初の部分は正常に機能しますが、たとえばWi-Fiを切り替えると、アプリがクラッシュします。これを修正するにはどうすればよいですか?また、さまざまなエラーを表示するにはどうすればよいですか?前もって感謝します!!これが私のコードです(これは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を使用する必要があります。URLからを作成し、URL接続を開始するNSURLRequestURLに渡します。[NSURLConnection connectionWithRequest:request delegate:self];

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 に答える