显示等待警报视图在负载

时间:2014-01-13 15:40:06

标签: ios objective-c alert wait cocoaasyncsocket

我希望当我的应用程序启动它时显示一个警报视图大约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 个答案:

答案 0 :(得分:3)

不要在主线程上使用sleep。永远。也不要从后台线程更新UI。

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

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

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:1)

你用你的方式阻止主线程。

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

答案 3 :(得分:0)

您可以使用performSelector:withObject:afterDelay:method。

相关问题