繁体   English   中英

iPhone Objective-C:将方法结合在一起

[英]iPhone Objective-C: combining methods together

我是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个单独的连接,因为我希望能够返回一个布尔值来验证连接是否成功。

如果有人可以告诉我如何将该过程编码为一个方法,我将非常感激。

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

将所有这些内容“内联”的方法是NSURLConnection上的sendSynchronousRequest:returningResponse:error

[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...

我个人鼓励您为这种异步方法寻找一种替代方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM