【问题标题】:Check whether NSURLConnection not success in iphone?检查 NSURLConnection 在 iphone 中是否不成功?
【发布时间】:2012-09-03 00:07:19
【问题描述】:
-(void)loadRequest:(NSString *)jsonString{
receivedData = [[NSMutableData alloc]init];
urlString = [[NSString alloc]initWithString:[NSString stringWithFormat:kURL]];
urlRequest=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
   requestInformation =[[NSMutableURLRequest alloc]initWithURL:urlRequest cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[requestInformation setValue:khttpValue forHTTPHeaderField:kContentType];
[requestInformation setValue:@"value1" forHTTPHeaderField:@"key1"];

[requestInformation setHTTPMethod:kPost];
jsonData= [[NSString stringWithFormat:@"json=%@",jsonString] dataUsingEncoding:NSUTF8StringEncoding];
[requestInformation setHTTPBody:jsonData];

connection = [[NSURLConnection alloc] initWithRequest:requestInformation delegate:self];
[connection start];
if(connection){
    NSLog(@"Connection succesfull");
}
else{
    NSLog(@"There is a error in connection");
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(onFailedToUpload) userInfo:nil repeats:NO];

}
}

如何检查 else 部分是否被执行。我给出的 URL 不正确,调用了 didfailwitherror 方法但没有执行 else 部分。

【问题讨论】:

标签: iphone objective-c ipad ios5 nsurlconnection


【解决方案1】:

据我所知,connection 对象总是被创建的。即使你的网址是错误的。委托didFailWithError 方法出现任何错误。您可能需要检查错误并正确进行。前任。如果超时,您可能需要在didFailWithError 委托中重试。对于其他错误类型的处理方式不同。

如果您想在将其传递给NSURLConnection 之前处理损坏或错误的网址,那么您需要自己做。

这里是使用NSURLConnection时对你有用的代表 -

- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response 
{
    NSLog("@Resp received");
    return;
}

- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data 
{
    NSLog("@Data received");
    return
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error 
{
    NSLog("@ERROR: Achtung !: %@",[error localizedDescription]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH , 0),, ^{
        NSLog(@"FinishedLoading: In bg thread, do something with data here");

        dispatch_async( dispatch_get_main_queue(), ^{
            NSLog(@"FinishedLoading: In Main thread, access the UI here");
        });
    });
}

【讨论】:

  • 感谢您的宝贵回复
猜你喜欢
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-20
  • 2013-08-26
  • 2019-07-01
  • 1970-01-01
相关资源
最近更新 更多