iPhone 子プロセスではNSURLConnectionののタイムアウトが検知できない?

タイムアウトが検知できないというか、delegateが何も通知されてきません。

実装は至ってシンプル

-(void)click:(UIButton*)button
{
    // サブスレッドを作成する
    [NSThread detachNewThreadSelector:@selector(doProcess) toTarget:self withObject:nil];
//    [self doProcess];
}

- (void)doProcess {
    // ここから追加
    NSURL *url = [NSURL URLWithString:@"http://localhost:5000/"];
    NSURLRequest *req=[NSURLRequest requestWithURL:url];
    NSURLConnection *conn=[[NSURLConnection alloc] 
                                    initWithRequest:req delegate:self];
    if (conn) {
        NSLog(@"start loading");
        receivedData = [[NSMutableData data] retain];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"receive response");
    [receivedData setLength:0];
}

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    NSLog(@"%@", [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding]);
}

サブプロセスからだと、ログは以下のものしかでません
2011-11-29 01:13:04.444 Sample01[98789:13003] start loading

もちろんサブプロセスではなく、メインスレッドであれば正しく動作します。
2011-11-29 01:23:50.675 Sample01[98997:f803] start loading
2011-11-29 01:23:51.182 Sample01[98997:f803] receive response
2011-11-29 01:23:51.183 Sample01[98997:f803] receive data
2011-11-29 01:23:51.183 Sample01[98997:f803] Succeeded! Received 1446 bytes of data

そもそもサブプロセスなんだから非同期の通信じゃなくてもよくて、
NSURL *theURL = [NSURL URLWithString:@"http://localhost:5000/"];
    NSURLRequest *req=[NSURLRequest requestWithURL:theURL];
 NSMutableData*      data;
    NSHTTPURLResponse*  resp;
    NSError*            err = nil; 
    data = [NSMutableData dataWithData:[NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:&err]];

    NSLog(@"Succeeded! Received %d bytes of data",[data length]);
    NSLog(@"%@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

これで正しく取得できました。

0 件のコメント:

コメントを投稿

ReactNativeでAndroid対応する話

前提 ReactNativeでiOS版のアプリをリリースしていて、Android版をリリースする話 トラブルシューティング Build.VERSION_CODES.Q が存在しないエラー compileSdkVersionを29以上にすると解決 メモリー足りないエラー Execu...