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

Objective-c how to update UI depending on background process

我正在开发一个 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 must be used from main thread only"

感谢您的帮助。

dispatch_async里面是正确的地方。您需要在 unreachableBlock.

中添加类似的块

如错误消息所述,您只能从主线程修改 Ui。

您必须在主线程上更新 UI。为此,您应该在检测到 wifi 为 connected/disconnected 时调用 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"]];
    });
};