0

重複の可能性:
HTTP 応答エラー ステータスでの NSURLConnection の使用のテスト

これは奇妙です。次のような非同期接続があります。

NSString *url=[NSString stringWithFormat:@"http://www.whatever.com/file"];

NSURL *url2=[NSURL URLWithString:url];
NSURLRequest *req=[[NSURLRequest alloc] initWithURL:url2];
NSURLConnection*con=[[NSURLConnection alloc] initWithRequest:req delegate:self];
[req release];

if(con){
    NSMutableData *data=[[NSMutableData alloc] init];
    self.receivedData=data;
    [data release];
}
else {
    UIAlertView*alert=[[UIAlertView alloc] initWithTitle:@"Error!" message:@"Unable to connect to server." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
}

次に、標準のデリゲート メソッドをいくつか用意します。

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[receivedData setLength:0];

}

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

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[connection release];
self.receivedData=nil;

UIAlertView*alert=[[UIAlertView alloc] initWithTitle:@"This app requires Internet" message:[NSString stringWithFormat: @"Connection failed.\n Please exit and check your\nInternet access."] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];

[alert show];
[alert release];

}

-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *payload=[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
self.downloaded=nil;
self.downloaded=payload;
[payload release];
[connection release];
self.receivedData=nil;

NSLog(@"This will display if connectionDidFinishLoading runs.");

}

ファイルがサーバー上になくても、最後にある NSLog が実行されています。なんで?何かがロードされているとは思わず、代わりにエラーと警告ビューが表示されました。

これらのメソッドは最初は明確に見えますが、非同期接続について理解していないことがここで起こっているに違いありません。

4

1 に答える 1

2

読み込みが完了しました。HTTPエラーで終了したという事実は重要ではありません。

didReceiveResponseで取得したNSHTTPResponseオブジェクトには.responseCode、404を含むプロパティが含まれます。

于 2011-07-11T17:24:39.313 に答える