Always got nil value from the function in iOS

后端 未结 2 728
无人及你
无人及你 2020-12-06 16:02

I\'m using AFNetworking for some GET queries. But my function always returns nil value. Where I was wrong?

+ (NSString *)getRequestFromUrl:(NSString *)reque         


        
2条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 16:31

    You're not seeing a result because the blocks that you pass in for success and failure run asynchronously; by the time your NSLog gets called, the web service won't have returned yet. If you move your NSLog inside of your success and failure blocks, you should see a result get output to your console.

    Because of the asynchronous nature of these calls, you won't be able to simply return the value from your method. Instead, you may want to take your own block as a parameter, which you can then call when you have a result. For example:

    + (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);
        }];
    }
    

    You would then call your method like so:

    [YourClass getRequestFromUrl:@"http://www.example.com" withCompletion:^(NSString *results){
        NSLog(@"Results: %@", results);
    }
    

    AFNetworking's sample project has an example of using a block parameter to return a value from your web service calls: https://github.com/AFNetworking/AFNetworking/blob/master/Example/Classes/Models/Post.m

提交回复
热议问题