我正在使用一个API,该API返回解析为字符串的JSON。然后,我想将此字符串用作另一个视图控制器上的标签。我尝试使用完成块,但无法正常工作,它不断返回“致命错误:预期的可选返回nil”,但我不知道在哪里。我假设它与异步调用有关,不允许异步类使用尚未返回API的String填充popup类。

    func summarizeArticle(finished: () -> Void) {
    let formatText = (searchText.text?.replacingOccurrences(of: " ", with: "_"))!
    articleNameFormatted = ("https://en.wikipedia.org/wiki/" + formatText)
    let request : NSMutableURLRequest = NSMutableURLRequest()
    request.url = NSURL(string: urlString + articleNameFormatted) as URL!
    request.httpMethod = "POST"
    let url = request.url
    URLSession.shared.dataTask(with:url!) { (data, response, error) in
        if error != nil {
            print(error!)
        } else {
            do {
                let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
                articleSummary = parsedData["sm_api_content"] as! String
                print(articleSummary)
            } catch let error as NSError {
                print(error)
            }
        }
        }.resume()
    finished()
}


@IBAction func summarizeButtonPressed(_ sender: Any) {
    self.view.endEditing(true)
    summarizeArticle{
        let popupVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "sbPopupVC") as! PopupViewController
        popupVC.view.frame = self.view.frame
        self.addChildViewController(popupVC)
        self.view.addSubview(popupVC.view)
        popupVC.didMove(toParentViewController: self)
    }
}


然后,第二个视图控制器使用此函数,该函数应该从以前的函数设置的全局变量中获取文本:

    override func viewDidLoad() {
    super.viewDidLoad()
    popupView.layer.cornerRadius = 10.0
    popupView.clipsToBounds = true

    summaryText.text = articleSummary

    view.backgroundColor = UIColor.black.withAlphaComponent(0.0)
    self.showAnimation()
}

最佳答案

代替将articleSummary设置为全局变量,请尝试以下操作:

1)将articleSummary本地化为summarizeArticle()函数。

2)在标识符为"sbPopupVC"的视图控制器的类定义中,添加一个名为articleSummaryText之类的实例变量。

3)删除summarizeArticle()上的完成处理程序,并将其中的所有代码移至URLSession API调用的完成块。

4)在该完成块中,在self.addChildViewController(popupVC)之前,添加以下行:popupVC.articleSummaryText = articleSummary

5)最后,在您的popupVC的viewDidLoad()中,设置summaryText.text = articleSummaryText

关于ios - 用NSURL的结果填充UIView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42195801/

10-12 03:37