我整个下午都在努力学习这个。
在这里举例:http://themainthread.com/blog/2012/09/communicating-with-blocks-in-objective-c.html,我设法设置一个回调来获取对我所拥有的Web服务的异步调用的结果。
Web服务接受一个关键代码,应用程序将其转换并将其传回以进行身份验证。
使用下面的代码,如何将方法从void更改为NSString,我可以调用它来返回我的密码?
-(void) showPassCode{
getAuthCodeAndMakePassCodeCompleteBlock callback = ^(BOOL wasSuccessful, NSString *passCode) {
if (wasSuccessful) {
NSLog(@"Code is: %@", passCode);
} else {
NSLog(@"Unable to fetch code. Try again.");
}
};
[self getAuthCodeAndMakePassCode:@"myAuthCode" withCallback:callback];
}
理想情况下,我希望它能够工作或看起来像这样:
-(NSString *) strPassCode{
getAuthCodeAndMakePassCodeCompleteBlock callback = ^(BOOL wasSuccessful, NSString *passCode) {
if (wasSuccessful) {
return passCode;
} else {
return nil;
}
};
[self getAuthCodeAndMakePassCode:@"myAuthCode" withCallback:callback];
}
答案 0 :(得分:0)
在不知道代码的细节以及如何查询服务器的情况下,我不得不想象它看起来像:
-(void)getAuthCodeWithCallback:(void (^)(NSString* authCode))callback
{
//make server call, synchronously in this example
NSString* codeReturnedFromServer = [self getServerCodeSynchronous];
callback(codeReturnedFromServer);
}
//some calling code
[self getAuthCodeWithCallback:^(NSString* authCode) {
NSLog(@"Code is: %@", authCode);
}];
如果从服务器获取auth代码的方法是异步的,它看起来像这样:
-(void)getAuthCodeWithCallback:(void (^)(NSString* authCode))callback
{
//make server call, asynchronously in this example
[self someMethodCallToQueryCodeFromServerWithCallback:^(NSError* error, NSString* code) {
if (error) {
//handle error
}
else
callback(code);
}
}