我正在使用AFNetworking进行一些GET查询。但我的函数总是返回nil值。哪里错了?
+ (NSString *)getRequestFromUrl:(NSString *)requestUrl {
NSString * completeRequestUrl = [NSString stringWithFormat:@"%@%@", BASE_URL, requestUrl];
__block NSString * results;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:completeRequestUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
results = [NSString stringWithFormat:@"%@", responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
results = [NSString stringWithFormat:@"Error"];
}];
NSLog(@"%@", results);
return results;
}
THX!阿尔乔姆。
答案 0 :(得分:6)
您没有看到结果,因为您为success
和failure
传入的块是异步运行的;当您的NSLog
被调用时,Web服务还没有返回。如果您在成功和失败块中移动NSLog
,您应该看到结果输出到您的控制台。
由于这些调用的异步性质,您将无法简单地从方法返回值。相反,您可能希望将自己的块作为参数,然后在获得结果时可以调用该参数。例如:
+ (void)getRequestFromUrl:(NSString *)requestUrl withCompletion:((void (^)(NSString *result))completion
{
NSString * completeRequestUrl = [NSString stringWithFormat:@"%@%@", BASE_URL, requestUrl];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:completeRequestUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *results = [NSString stringWithFormat:@"%@", responseObject];
if (completion)
completion(results);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSString *results = [NSString stringWithFormat:@"Error"];
if (completion)
completion(results);
}];
}
然后您可以这样调用您的方法:
[YourClass getRequestFromUrl:@"http://www.example.com" withCompletion:^(NSString *results){
NSLog(@"Results: %@", results);
}
AFNetworking的示例项目有一个使用块参数从Web服务调用中返回值的示例:https://github.com/AFNetworking/AFNetworking/blob/master/Example/Classes/Models/Post.m
答案 1 :(得分:0)
- (void)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
[_manager POST:[NSString stringWithFormat:@"%@%@",API_HOST,URLString] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
block(formData);
} progress:^(NSProgress * _Nonnull uploadProgress1) {
uploadProgress(uploadProgress1);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(task,responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(task,error);
}];
}