【问题标题】:ios synchronous network request handler returning resultios同步网络请求处理程序返回结果
【发布时间】:2016-08-27 02:39:10
【问题描述】:

我遇到的问题是我的应用程序有一个线程需要定期在循环内发出一系列网络请求。由于这是在一个单独的线程内,并且由于请求的性质(对本地网络上的设备并且响应很简单),我想同步执行此操作。网络通信是一个单独的networking 类而不是databaseController 类。

我无法让networking 类中的方法从完成处理程序内部返回某些内容

+ (void)GetMessages
{
   NSURLSession *session = [NSURLSession sharedSession];
   NSURLRequest *request = [networking makeAuthenticatedRequest:@"subpath.html"];
   //NSString* returnable;
   NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                   completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {
                                  NSString* newStr = [[NSString alloc] initWithData:data
                                                         encoding:NSUTF8StringEncoding];
                                  //returnable = newStr;
                                  //return(newStr)
                                  NSLog(newStr);
                              }];
   [task resume];
}

上面的代码可以工作,但是除了打印请求的结果之外什么都不做。当我尝试任何注释掉的添加和必要的更改时,没有任何效果。我什至尝试传递对调用对象的引用并更新用于将 newStr 存储在完成处理程序中的属性,但即使这样也不起作用。

我正在尝试的可能吗?如果有怎么办?

我可能应该补充一点,代码需要与 ios 7-9 兼容。

【问题讨论】:

    标签: ios objective-c multithreading networking


    【解决方案1】:

    您需要执行以下操作:

    NSURLSession *session = [NSURLSession sharedSession];
    NSMutableURLRequest *request =
    [NSMutableURLRequest requestWithURL:[NSURL
                                         URLWithString:@"https://www.yahoo.com"]
                    cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                        timeoutInterval:10
     ];
    
    __block NSString* returnable; // notice the __block here
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                    completionHandler:
                    ^(NSData *data, NSURLResponse *response, NSError *error) {
                     NSString* newStr = [[NSString alloc] initWithData:data
                                        encoding:NSUTF8StringEncoding];
                     returnable = newStr;
                     // return(newStr); You cant return this here. Because the callback doesn't permit you to do so.
                     NSLog(@"%@", newStr);
            }];
    [task resume];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多