iphone - 检查 NSURLConnection 是否在 iphone 中不成功?

标签 iphone objective-c ipad ios5 nsurlconnection

-(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 方法但没有执行其他部分。

最佳答案

据我所知,总是会创建connection 对象。即使你的网址是错误的。委托(delegate) didFailWithError 方法出现任何错误。您可能需要检查错误并适本地继续。前任。如果超时,您可能想在 didFailWithError 委托(delegate)中重试。对于其他错误类型,处理方式不同。

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

以下是在使用 NSURLConnection 时对您有用的委托(delegate) -

- (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");
        });
    });
}

关于iphone - 检查 NSURLConnection 是否在 iphone 中不成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12346359/

相关文章:

iphone - 如何在 MKMapView 内用彩色线连接 2 个注释?

objective-c - 存储 UILocalNotification 以便于处理

objective-c - 枚举值 : NSInteger or int?

iphone - 更改重复使用的单元格的类型?

iphone - Xcode 和 Git 源代码管理 : “The working copy XXXXX failed to commit files”

ios - 在 Swift 中关闭 UIImagePickerController 后如何切换到另一个 View ?

ios - 运行 Apple 的默认操作扩展代码会引发异常或不执行任何操作

ios - SLRequest - Twitter 返回代码 215(错误的身份验证数据)

ios - iPhone 应用程序使用什么 dpi 分辨率?

iphone - Mac 上的 iOS 模拟器不显示电子邮件或 ActiveSync 选项