调用的值方法未返回

时间:2015-07-23 07:25:55

标签: objective-c rest return-value

我有这个执行REST调用的类。

- (NSString*)cerca:(NSString*)email{
if ([[Utility sharedUtility] connected]) {
    HttpClient *self = [HttpClient sharedHTTPClient];
    [self.requestSerializer setValue:[self getUserAgent] forHTTPHeaderField:@"User-Agent"];
    [self.requestSerializer setValue:NST_CODE forHTTPHeaderField:@"Nst-Code"];
    [self.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"nst_id"] forHTTPHeaderField:@"Nst-Id"];
    [self.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"api_key"] forHTTPHeaderField:@"Api-Key"];

    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"email"] = email;

    __block NSString *result;

    [self POST:@"get_info" parameters:parameters
       success:^(NSURLSessionDataTask *task, id responseObject) {

          result = responseObject;


       } failure:^(NSURLSessionDataTask *task, NSError *error) {


       }]; 
return result;

}

该调用返回一个JSON。我的问题是,当我返回结果时;没有任何内容传递给调用方法。 你能告诉我为什么吗?

调用方法是

HttpClient *client = [HttpClient alloc];
NSString *result = [client cerca:email];

3 个答案:

答案 0 :(得分:1)

您正在调用的方法是异步调用,这意味着返回后会产生结果。您需要更改方法以接受块参数并在回调中返回结果。

- (void)cerca:(NSString*)email callback:(void (^)(id result)) callback {
   if ([[Utility sharedUtility] connected]) {
     ...

     [self POST:@"get_info" parameters:parameters
     success:^(NSURLSessionDataTask *task, id responseObject) {
        if (callback) { 
          callback(responseObject)
        }
     } failure:^(NSURLSessionDataTask *task, NSError *error) {


     }]; 
  }
}

要调用您要执行的方法:

[client cerca:email completion:^(NSString *response) {
   // Do what you want with the response.
}];

答案 1 :(得分:0)

因为self POST调用是异步的,并且在它有时间分配之前返回result。您需要重建- (NSString*)cerca:(NSString*)email方法,以便以某种方式处理此异步。最简单的方法通常是更改方法,以便在参数中使用完成块。也许是这样的:

        - (void)cerca:(NSString *)email completion:(void (^)(NSString *res))completion {
            [self POST:@"get_info" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
                if (completion) {
                    completion(responseObject);
                }
            }failure:^(NSURLSessionDataTask *task, NSError *error) {
                if (completion){
                    completion(nil);
                }
            }];
        }

答案 2 :(得分:0)

我改变了方法

- (NSString*)cerca:(NSString*)email completion:(void (^)(NSString *res))completion {

但我不明白该怎么称呼它。适应症?

[client cerca:email completion:nil];