【问题标题】:Return value in NSURLSession ErrorNSURLSession 错误中的返回值
【发布时间】:2016-01-21 06:08:18
【问题描述】:

尝试返回 responseString 时出现以下错误

不兼容的块指针类型发送 'NSString *(^)(NSData *__strong, NSURLResponse *__strong, NSError *__strong)' 到类型参数 'void (^)(NSData *__strong, NSURLResponse *__strong, NSError *__strong)'

我从 Suppose AViewController 类中调用它

NSString *responseString=[self callAPI];

下面是我在 BViewModel 类中的代码:

-(NSString* )callAPI
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:@"http://appersgroup.com/talkawalk/login.php?email=twalknet@gmail.com&password=123456&latitude=52.486245&longitude=13.327496&device_token=show"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];
    /* NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
     @"IOS TYPE", @"typemap",
     nil];
     NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
     [request setHTTPBody:postData];
     */

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        if([responseString rangeOfString:@"nil"].location != NSNotFound)
        {
            NSString * newResponse =  [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

            responseString = newResponse;
        }

        NSLog(@"%@",responseString);
        NSLog(@"response %@",response);
        NSLog(@"error %@",error);

        return responseString;//adding this line give me error ? how to return value 


    }];

    [postDataTask resume];
}

【问题讨论】:

    标签: ios iphone xcode nsurlsession


    【解决方案1】:

    你可以像这样使用这个方法:

    -(void)callAPIWithCompletionHandler : (void (^) (NSString * strResponse)) completionHandler
    {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
        NSURL *url = [NSURL URLWithString:@"http://appersgroup.com/talkawalk/login.php?email=twalknet@gmail.com&password=123456&latitude=52.486245&longitude=13.327496&device_token=show"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval:60.0];
    
        [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    
        [request setHTTPMethod:@"POST"];
        /* NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
         @"IOS TYPE", @"typemap",
         nil];
         NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
         [request setHTTPBody:postData];
         */
    
        NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    
            NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
            if([responseString rangeOfString:@"nil"].location != NSNotFound)
            {
                NSString * newResponse =  [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    
                responseString = newResponse;
            }
    
            NSLog(@"%@",responseString);
            NSLog(@"response %@",response);
            NSLog(@"error %@",error);
    
            completionHandler(responseString);
    
        }];
    
        [postDataTask resume];
    }
    

    调用此方法并返回如下响应:

    [self callAPIWithCompletionHandler:^(NSString *strResponse) {
    
            NSString *responseString = strResponse;
    }];
    

    假设此方法在ViewControllerA 中实现,并且您想从ViewControllerB 调用此方法。

    然后在ViewControllerB 中导入ViewControllerA 并在ViewControllerB 中创建ViewControllerA 的实例。

    ViewControllerA *vcA = [[ViewControllerA alloc] init];
    [vcA callAPIWithCompletionHandler:^(NSString *strResponse) {
    
            NSString *responseString = strResponse;
    }];
    

    【讨论】:

    • 请检查我的编辑问题,我需要从不同的类调用这个API,那么我如何在那个类中获得返回响应?
    • @iphonemaclover 他已经给你看了。看看他回答中的最后一段代码。这就是你必须这样做的方式
    • 我试图在 textview 中显示输出字符串,但它会杀死它,请检查 NSLog(@"viewcontroller response =%@",responseString); txt_output.text=[NSString stringWithFormat:@"%@",strResponse]; txt_output 在我的 ViewcontrollerB 中,我从 ViewcontrollerA 返回 NSString *returnstring=[NSString stringWithFormat:@"request=%@ responstring=%@ error=%@",request,responseString,error];完成处理程序(响应字符串);
    • 请发布相关问题并发布崩溃日志。所以我会帮你的。
    • 请发布相关问题并发布崩溃日志。所以我会帮你的。
    【解决方案2】:

    您正试图从一个不应返回任何值的块中返回一个字符串。这就是编译器给你错误的原因。该块将异步执行,因此您正在做的事情没有意义。您确实需要熟悉块的工作原理,尤其是当它们异步执行时。

    阅读:Working with blocks

    【讨论】:

    • 如何解决?我需要返回一个字符串一次,我得到响应
    • 您将无法从该函数返回字符串。从块中继续执行
    • 您可以例如从该块发布通知,并将您的响应字符串放入通知中。你明白了吗?
    猜你喜欢
    • 2017-07-27
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多