1

我希望当我的应用程序启动时它显示大约 5 秒的警报视图,然后根据后台进程的结果,它将显示另一个警报视图。

我遇到的问题是,当我尝试使用 Sleep 来等待后台进程发生时。第一个警报不显示并等待 5 秒。该应用程序显示应用程序的第一个视图,然后在 5 秒后短暂显示第一个警报。

我需要做什么来执行我想要的。

这是我的代码。

- (void)viewDidAppear:(BOOL)animated
{
    SSGlobalSettings *connSettings = [SSGlobalSettings sharedManager];

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Connecting" message:@"Please wait, while your device connects" delegate:Nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alertView show];

    [NSThread sleepForTimeInterval:5.0f];

    [alertView dismissWithClickedButtonIndex: alertView.cancelButtonIndex animated: YES];

    if ([connSettings.connectionStatus  isEqual: @"Not Found"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Connection Failed" message:@"Cannot find your device on the network" delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alertView show];
    }
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Connection Success" message:@"WYour device has been found on the network" delegate:@"OK" cancelButtonTitle:nil otherButtonTitles: nil];
        [alertView show];
    }
}
4

4 回答 4

3

不要在主线程上使用睡眠。曾经。也不要从后台线程更新 UI。

您要做的是在主线程上显示警报并返回。

然后,当您的网络代码完成时,让它向主线程发送一条消息。在主线程中,当您收到通知已完成时,请删除警报。

于 2014-01-13T16:00:45.440 回答
1

它无法正常工作,因为您正试图告诉应用程序的主线程进入睡眠状态。如果您要让该线程进入睡眠状态,那么您很可能不允许在此期间发生任何 UI 更新,因为所有 UI 更新都发生在主线程上。

您需要做的是将显示第二个 UIAlertView 的代码移动到第二个方法,然后调用该方法- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay,将第二个方法传递给选择器,并延迟 5 秒。确保您删除了睡眠主线程的调用。

但是,这似乎仍然是一种不好的做法,因为此操作应该在您的后台任务完成时发生。因此,如果可以,您应该运行代码以在完成该任务后显示第二个警报视图,该任务很可能会在不同的时间内完成。

于 2014-01-13T15:50:15.527 回答
1

你以你的方式阻塞了主线程。

我认为您似乎只是希望用户在前 5 秒之前不要做任何事情(让您连接成功?),如果是这样,有很多方法可以做到这一点,例如只在窗口顶部显示一个视图,在您希望用户可以做某事之前,您可以在该视图上显示消失按钮或立即将其消失。

于 2014-01-13T15:50:22.543 回答
0

您可以改用 performSelector:withObject:afterDelay: 方法。

于 2014-01-13T15:48:47.633 回答