【问题标题】:Run code on background and get return code在后台运行代码并获取返回码
【发布时间】:2013-05-23 10:01:21
【问题描述】:

我有这个方法

    - (BOOL)connectedToInternet
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
                                    [NSURL URLWithString:@"http://www.google.com/"]];

    [request setHTTPMethod:@"HEAD"];

    NSHTTPURLResponse *response;

    [NSURLConnection sendSynchronousRequest:request
                          returningResponse:&response error: NULL];

    return ([response statusCode] == 200) ? YES : NO;
}

该方法需要几秒钟才能完成,我在一个简单的条件下使用它来了解我是否有互联网连接。

有什么方法可以在后台线程中完成,而无需更改所有代码。

我这样称呼它

if([self connectedToInternet])

因此,如果我在后台线程中执行此操作,我将无法获得返回值,然后我的方法也无法返回该值。

如果我必须改变一切,那是不值得的。

希望你能理解我的问题并感谢您的帮助。

【问题讨论】:

  • 为什么不能在后台线程运行它的返回值?
  • 如果我使用 [NSThread detachNewThreadSelector:] 运行它,我无法在同一方法上获得返回值。我将不得不将返回发送到另一种方法,然后调用将无法正常工作。
  • @userXXX 回调呢?
  • 我认为正确的方法在这里详述:stackoverflow.com/questions/8036895/read-nsurlresponse

标签: ios objective-c


【解决方案1】:

请在 Apple 的“可达性”Code Sample 中注意 reachabilityWithAddress: 方法。

【讨论】:

    【解决方案2】:

    你可以使用积木来做类似的事情;

    定义(.h)

    + (void)isConnectedToInternet:(void (^)(BOOL connected))block;
    

    实现 (.m)

    + (void)isConnectedToInternet:(void (^)(BOOL))block
    {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
                                        [NSURL URLWithString:@"http://www.google.com/"]];
    
        [request setHTTPMethod:@"HEAD"];
    
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
            NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    
            if (block) {
                block( ([httpResponse statusCode] == 200) ? YES : NO);
            }
        }];
    }
    

    然后这样称呼它

    [MyClass isConnectedToInternet:^(BOOL connected) {
            if (connected) {
                // do stuff;
            }
        }];
    

    【讨论】:

    • 这可能是我需要的,但 xcode 说我无法访问块内的响应 NSURLResponse 没有可见界面...
    • 你也应该检查错误,如果错误!= nil,connected = NO;不客气:)
    • 我认为没有必要再做,没有互联网连接也能正常工作。
    【解决方案3】:

    我不知道你到底想做什么,但你想用的大概是:

    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_async(queue, ^{
        //your asynchronous code here
    });
    

    但是通过使用 if 条件,您需要结果才能继续,不是吗?那么为什么要在后台运行代码呢?

    【讨论】:

    • 这就是重点,我需要结果但我不想阻塞 ui 线程
    【解决方案4】:

    我会建议你正在实施的方法来了解“是否连接互联网”不是最优化的方法......几天前我也尝试实施同样的事情......我遇到了几个解决方案,通过 Internet.. 我在我的博客上写过.. Checking Internet connection in cocoa.

    了解网络是否连接的首选方法是使用 Reachability 类。您可以从以下代码中获得使用它的线索:NetworkCheckUtility.

    希望这会有所帮助:-)

    【讨论】:

      猜你喜欢
      • 2018-02-23
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 2011-05-23
      • 2017-09-11
      • 1970-01-01
      • 2013-07-14
      相关资源
      最近更新 更多