始终从iOS中的函数获得零值
我正在使用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; }
谢谢! 阿尔乔姆。
您没有看到结果,因为您为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
- (void)POST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id 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 _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); }]; }