执行自动转场

Performing an automatic segue

我正在下载远程 JSON 数据并希望我的加载屏幕一直显示到下载完成。一旦我的解析方法完成 运行,应该调用 segue 以自动移动到下一个视图。

我已确认我的数据正在正确下载和解析。当我抛出断点​​时,甚至会调用我的 performSegue 函数。但是应用程序仍然没有移动到下一个视图。

这里是我调用解析方法然后立即调用所需的 segue 的地方:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    downloadSources(atURL: "https://newsapi.org/v1/sources?language=en")
    performSegue(withIdentifier: "loadingFinished", sender: self)
}

仅供参考,如果您需要,这里是我完整的解析方法:

func downloadSources(atURL urlString: String) {
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    if let validURL = URL(string: urlString) {
        var request = URLRequest(url: validURL)
        request.setValue("49fcb8e0fa604e7aa461ee4f22124177", forHTTPHeaderField: "X-Api-Key")
        request.httpMethod = "GET"

        let task = session.dataTask(with: request) { (data, response, error) in
            if error != nil {
                assertionFailure()
                return
            }

            guard let response = response as? HTTPURLResponse,
            response.statusCode == 200,
            let data = data

                else {
                    assertionFailure()
                    return
            }

            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                    guard let sources = json["sources"] as? [[String: Any]]

                        else {
                            assertionFailure()
                            return
                    }

                    for source in sources {
                        guard let id = source["id"] as? String,
                        let name = source["name"] as? String,
                        let description = source["description"] as? String

                            else {
                                assertionFailure()
                                return
                        }

                        self.sources.append(Source(id: id, name: name, description: description))
                    }
                }
            }

            catch {
                print(error.localizedDescription)
                assertionFailure()
            }
        }

        task.resume()
    }
}

提前致谢。

听起来闭包回调就是你想要的。

typealias CompletionHandler = ((_ success:Bool) -> Void)?

override func viewDidLoad() {
    super.viewDidLoad()
        downloadSources(atURL: "www.example.com", completion: {
            if success {
                performSegue(withIdentifier: "loadingFinished", sender: self)
                return
            }
            // otherwise deal with failure
    })
}

func downloadSources(atURL urlString: String, completion: CompletionHandler) {
    if error != nil {
        completion?(false)
        return
    }
    // finish downlaod
    completion?(true)
}