4
-(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 部分は実行されません。

4

1 に答える 1

3

私の知る限り、connectionオブジェクトは常に作成されます。あなたのURLでさえ間違っています。デリゲートdidFailWithErrorメソッドに発生するすべてのエラー。おそらく、エラーを調べて適切に続行する必要があります。元。タイムアウトの場合は、didFailWithErrorデリゲートで再試行することをお勧めします。他のエラー タイプでは、処理が異なります。

に渡す前に壊れた URL や不正な URL を処理したい場合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-09-10T06:49:26.423 に答える