Json Swift上的Access变量do catch语句

Json Swift上的Access变量do catch语句,json,swift,xcode,do-catch,Json,Swift,Xcode,Do Catch,我正在开发一个json解析的应用程序。我将AlertView用于json消息。但是我无法访问AlertView中的jsonmessage变量。如果将AlertView放入,是否会出现以下错误:“libc++abi.dylib:以NSException类型的未捕获异常终止 (lldb)” 对不起,我的英语不好。这是我的代码: request.httpBody = postParameters.data(using: String.Encoding.utf8) let tas

我正在开发一个json解析的应用程序。我将AlertView用于json消息。但是我无法访问AlertView中的jsonmessage变量。如果将AlertView放入,是否会出现以下错误:“libc++abi.dylib:以NSException类型的未捕获异常终止 (lldb)” 对不起,我的英语不好。这是我的代码:

request.httpBody = postParameters.data(using: String.Encoding.utf8)
            let task = URLSession.shared.dataTask(with:request as URLRequest){
                data, response, error in
                if error != nil{
                    print("error is \(String(describing: error))")
                    return;
                }

                do {

                    let myJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                    if let parseJSON = myJSON {
                        var jsonmessage : String!
                        jsonmessage = parseJSON["message"] as! String?
                        print(jsonmessage)

                    }
                } catch {

                }
            }
            task.resume()
            let alert = UIAlertController(title: "Alert", message: jsonmessage /*not accessible*/ , preferredStyle: .alert)
        alert.addAction(UIAlertAction(title:"Ok", style:UIAlertActionStyle.default, handler:{ (UIAlertAction) in
            _ = self.navigationController?.popToRootViewController(animated: true)
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
        }))
            self.present(alert, animated: true, completion: nil)

首先,您正在执行一个异步请求。一旦得到响应,就会设置jsonmessage变量。但在发生这种情况之前,您需要创建UIAlertController。我猜您希望在收到响应后显示警报

此外,您不能在jsonmessage变量的作用域之外访问该变量。要解决此问题,请移动
var jsonmessage:String以便它与UIAlertController属于同一范围


您应该能够将警报移动到do catch语句中,但必须确保警报显示在主线程上。

因为您发现无法从尝试访问jsonMessage的位置访问它

这是因为以下几个原因:

  • 请求是在后台运行的异步任务,需要一些时间才能完成。因此,警报视图代码实际上在返回jsonMessage之前运行

  • 变量jsonMessage也超出了您试图调用它的范围

  • 要帮助解释:

    let task = URLSession.shared.dataTask(with:request as URLRequest){
                data, response, error in
    
         let fakeMessage = "hi"
         // data, response, error and fakeMessage only exist here upto the closing bracket. 
    }
    task.resume()
    
    // fakeMessage doesn't exist here at all. 
    
    要解决您的问题,您可以在闭包中显示您的警报(我在这里放置了fakeMessage),也可以使用completionHandler在jsonMessage就绪时返回jsonMessage,然后显示警报

    方法1

    let task = URLSession.shared.dataTask(with:request as URLRequest){
                data, response, error in
                if error != nil{
                    print("error is \(String(describing: error))")
                    return;
                }
    
                do {
    
                    let myJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                    if let parseJSON = myJSON {
                        var jsonmessage : String!
                        jsonmessage = parseJSON["message"] as! String?
    
                        DispatchQueue.main.async {
                             // some helper function to show a basic alert
                             self.presentAlert(title: "Response", message: jsonMessage)
                        }
    
                    }
                } catch {
    
                }
            }
            task.resume()
    
    方法2

    func fetchSomething(completion: @escaping (String -> Void)?) {
        // setup request
        let task = URLSession.shared.dataTask(with:request as URLRequest){
                data, response, error in
    
         let fakeMessage = "hi"
         completion(fakeMessage)
        }
        task.resume()
    }
    
    那么你可以这样使用它

    self.fetchSomething { response in 
        DispatchQueue.main.async {
            // some helper function to show a basic alert
            self.presentAlert(title: "Response", message: jsonMessage)
        }
    }    
    

    请全局定义此变量“jsonmessage”。当我定义global@KhushbuThanks时,alertview中将显示空文本!这是有效的。