【问题标题】:How could connectionDidFinishLoading: run if no file is found on server? [duplicate]如果在服务器上找不到文件,connectionDidFinishLoading: 如何运行? [复制]
【发布时间】:2011-10-02 23:48:13
【问题描述】:

可能重复:
Testing use of NSURLConnection with HTTP response error statuses

这很奇怪;我有一个这样的异步连接:

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 正在运行,即使文件不在服务器上。为什么?我不希望它加载任何东西,而是导致错误和警报视图。

这些方法一开始看起来很清楚,但这里肯定有一些我没有了解异步连接的事情。

【问题讨论】:

标签: objective-c ios nsconnection


【解决方案1】:

它确实完成了加载。它以 HTTP 错误结束的事实是无关紧要的。

您在 didReceiveResponse 中获得的 NSHTTPResponse 对象将有一个 .responseCode 属性,其中包含 404。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 2015-11-12
    • 2014-10-16
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2012-10-10
    相关资源
    最近更新 更多