由于我是IOS的新手,而AFNetworking 3,0是新手,所以我不知道如何从AFHTTPSessionManager检索数据。
我必须关注以下消息,我想返回结果
- (NSString *) makeServiceCall;
{
NSString *response = @"";
@try {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager
POST:self.url.absoluteString
parameters:self.parameters
progress:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"Success: %@", responseObject);}
failure:^(NSURLSessionDataTask * task, NSError * error) {
NSLog(@"Error: %@", error);
}];
[AFHTTPSessionManager manager].securityPolicy.allowInvalidCertificates = YES;
}
@catch (NSException *exception) {
NSLog(@"%@", exception.reason);
}
}
最佳答案
方法AFHTTPSessionManager POST:parameters:progress:success:failure:
是异步方法。
您尝试做的是从调用它的方法中返回一个字符串。由于该方法将在下载开始之前完成,因此将无法使用。
您需要使用类似以下的完成代码块来调用它...
- (void)getStringWithCompletionHandler:(void (^)(id))completion {
NSLog(@"Method started");
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager
POST:self.url.absoluteString
parameters:self.parameters
progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"Download underway");
}
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"Download successful");
completion(responseObject);
}
failure:^(NSURLSessionDataTask * task, NSError * error) {
NSLog(@"Error");
}];
// trying to return a string here won't work because the download hasn't finished yet.
// You can see the order of things happening by adding logs...
NSLog(@"Method finished");
}
此代码中的日志顺序为...
如您所见,由于下载尚未完成,尝试在方法末尾返回的操作无效。