Objective-c如何根据后台进程更新UI

时间:2018-04-27 13:30:27

标签: ios objective-c networking reachability

我正在开发一款iPad应用程序而且遇到了一个问题。我使用Reachability检查设备是否连接到网络(工作正常),我想更新图像视图,以便在网络断开连接时将其从wifi图标传递到无wifi图标。所以我发现我可以做一个后台进程,不断检查设备是否像这样连接:

// Allocate a reachability object
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];

// Set the blocks
reach.reachableBlock = ^(Reachability*reach)
{

    dispatch_async(dispatch_get_main_queue(), ^{
        connectivity = true;
        NSLog(@"REACHABLE!");
    });
};

reach.unreachableBlock = ^(Reachability*reach)
{
    connectivity = false;
    NSLog(@"UNREACHABLE!");
};
// Start the notifier, which will cause the reachability object to retain itself!
[reach startNotifier];

这有效,但我不知道在哪里进行图像修改以使其正常工作,因为如果我把它放在NSLog()之前,我得到“imageView setImage只能从主线程使用”

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

您必须更新主线程上的UI。为此,您应该在检测到wifi已连接/断开连接时调用dispatch_async(dispatch_get_main_queue()),然后相应地更新您的图像。像这样:

reach.reachableBlock = ^(Reachability*reach)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        connectivity = true;
        NSLog(@"REACHABLE!");
        [yourImage setImage:[UIImage imageNamed:@"withWifi"]];
    });
};

reach.unreachableBlock = ^(Reachability*reach)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        connectivity = false;
        NSLog(@"UNREACHABLE!");
        [yourImage setImage:[UIImage imageNamed:@"noWifi"]];
    });
};

答案 1 :(得分:0)

dispatch_async内的

是正确的位置。您需要在unreachableBlock中添加类似的块。

正如错误msg所说,你只能从主线程修改Ui。

相关问题