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”方法结束。我想在一个方法中拥有所有这些代码。不是 2 个单独的,因为我希望能够返回一个布尔值来验证连接是否成功。

如果有人能告诉我如何将此过程编码为一个方法,我将不胜感激。

4

1 回答 1

1

如果您真的希望将代码全部集成到一个方法中,那么您正在谈论可能阻塞所有 UI 等等,以同步 HTTP 请求方法和响应调用。

将这一切“内联”的方法是 sendSynchronousRequest:returningResponse:error on NSURLConnection

[NSURLConnection sendSynchronousRequest:returningResponse:error:]

IE

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 回答