【问题标题】:How to Complete Async call before app loads?如何在应用加载之前完成异步调用?
【发布时间】:2016-09-03 02:14:45
【问题描述】:

我找不到这个问题的答案可能是因为我不太确定我在寻找什么,因为我几周前才开始编程。

我的故事板入口点需要我从异步会话和 JSON 解析中获得的数据。然后,一旦它获得数据,它就会将其存储到 NSUserDefaults 中,因此它不必再次进行异步调用,并且应用程序可以随时访问该数据。

我将异步调用放在情节提要入口点的 viewdidload 中,因为据我所知,这就是应用程序的启动位置。问题是在应用第二次启动之前数据不会显示。

我从异步调用中获得的数据每月仅更改一次,因此不一定对时间敏感。

如何在异步调用完成之前延迟应用程序到达情节提要入口点?

这是正确的方法吗?

我应该切换到同步调用吗?

如果我将故事板入口点更改为看起来像正在加载应用程序的视图控制器,然后当异步调用完成时,使用完成处理程序对需要异步调用完成的视图控制器执行 segue?

【问题讨论】:

  • @LeoDabus 是否有检测首次启动的功能还是我必须创建一个?
  • 您可以使用 NSUserDefaults 保存第一次启动日期,并且仅在 key 为 nil 时才保存
  • 所以当加载它时,如果日期为 nil 则意味着它是第一次启动

标签: swift


【解决方案1】:

感谢 Leo 的工作。

Storing a variable when the app is first installed

我在这里做了两件事。首先,我创建了一个新的视图控制器,它将在完成时执行异步调用并转到我的主视图控制器。然后我使用上面的链接解决方案检测它是否是第一次启动。两者一起工作。

import Foundation
import UIKit

class FirstLoad: UIViewController {

var installedDate: NSDate? {
    get {
        return NSUserDefaults().objectForKey("installedDateKey") as? NSDate
    }
    set {
        NSUserDefaults().setObject(newValue, forKey: "installedDateKey")
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidAppear(animated: Bool) {
    firstLoad()
}

func firstLoad() {
    if installedDate == nil {
        installedDate = NSDate()

        parseData(heroesDataProject) { heroesArrayFromParse in             //this function gets my json and the following code is executed after completion

            saveToDefaults("heroesOriginal")
            print("First Run")
            self.performSegueWithIdentifier("firstLoadToHomeMenu", sender: nil)
        }

    } else {
        print("Not first run, installd on \(installedDate!)")
        loadFromDefaults(userProfile)
        performSegueWithIdentifier("firstLoadToHomeMenu", sender: nil)

    }
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多