1

私は Objective-C の完全な初心者なので、これは多くの人にとって非常にばかげた質問かもしれません。

現在、「サインイン」ボタンのあるビューがあり、クリックすると、以下で定義した sigupUp IBAction がアクティブになります。基本的に、このメソッドは JSON 呼び出しを行い、ユーザーに関するデータを取得する必要があります。

したがって、現在、私のコードは次のようになります。

-(IBAction)signIn:(id)sender{

//run registration API call

//establish connection
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
 NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.apicallhere.com/api/auth"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
 [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];

[[NSURLConnection alloc]initWithRequest:request delegate:self];
responseData = [[NSMutableData data] retain];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{[responseData setLength:0];}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{[responseData appendData:data];}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{/*NSLog(@"%@",error);*/}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *response=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
....code carries on from here.
}

ご覧のとおり、私のコードの問題は、「SignUp」メソッドを介して開始されたにもかかわらず、「connectionDidFinishLoading」メソッドで終了することです。このすべてのコードを 1 つのメソッドにまとめたいと考えています。接続が成功したかどうかを確認するブール値を返すことができるようにしたいので、2 つの別々のものではありません。

この手順を 1 つのメソッドにコード化する方法を誰か教えていただければ幸いです。

4

1 に答える 1

1

本当にすべてのコードを 1 つのメソッドにまとめたい場合は、同期 HTTP 要求メソッドと応答呼び出しですべての UI などを潜在的にブロックすることについて話していることになります。

これをすべて「インライン」にする方法は、sendSynchronousRequest:returningResponse:error on NSURLConnection です。

[NSURLConnection sendSynchronousRequest:returningResponse:error:]

すなわち

NSError *error;
NSURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
... do something with the NSURLResponse to enjoy with your data appropriately...

個人的には、非同期メソッドに対するこの種のほとんどの代替手段を検討することをお勧めします。

于 2010-07-13T02:13:43.603 に答える