我完全是 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 个单独的,因为我希望能够返回一个布尔值来验证连接是否成功。
如果有人能告诉我如何将此过程编码为一个方法,我将不胜感激。