是否可以在应用加载数据和冻结时显示警报?

时间:2015-09-30 20:50:44

标签: ios swift uitableview uialertview

我有一个从互联网上加载数据的应用。从互联网上加载数据时,应用程序正在冻结。是否可以在加载时显示警报视图?你可以在上面看到didSelectRowAtIndexPath:func。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath)! as UITableViewCell
        let text = cell.textLabel?.text!
        let indexNumber = towersNameArray.indexOf(text!)
        PlayData.TowerAddress = towersAddressArray[indexNumber!] //Dataloading
        PlayData.TowerName = towersNameArray[indexNumber!] //Dataloading
        if #available(iOS 8.0, *) {
            let alertController = UIAlertController(title: "Loading...", message: "Please Wait", preferredStyle: .Alert)
            self.presentViewController(alertController, animated: true, completion: nil)
            let delay = 2.5 * Double(NSEC_PER_SEC)
            let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
            dispatch_after(time, dispatch_get_main_queue(), {
                alertController.dismissViewControllerAnimated(true, completion: nil)
            })
            tabBarController?.selectedIndex = 1


        } else {
            // Fallback on earlier versions
        }



    }

2 个答案:

答案 0 :(得分:4)

您应该在后台线程中加载数据,如下所示:

//display an alert here if you need

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    //load stuff from internet here, don't display an alert

    dispatch_async(dispatch_get_main_queue(), {
        //display an alert here if you need to
    })
})

//display an alert here if you need.

可替换地:

您可以在开始加载内容之前约5秒钟后设置定时器,在内容完成后,您可以使定时器无效。这样,如果内容在5秒内没有加载,计时器将会触发,如果加载速度更快,计时器将不会触发。

func load() {
    self.timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "timerDone", userInfo: nil, repeats: false)
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        //load stuff from internet here

        dispatch_async(dispatch_get_main_queue(), {
            self.timer.invalidate()
        })
    })
}

func timerDone() {
    //display alert here
}

答案 1 :(得分:0)

为了用另一种方法解决它,我在加载方法之前将加载数据从互联网部分移动到调度部分。通过使用这种方式,警报在数据加载时离开。(如果我输入的时间少于加载计时器的时间)