将JSON数据从HTTP请求传递到Swift 3中的另一个视图控制器

时间:2017-08-30 08:44:54

标签: json swift

如何将HTTP请求中的JSON数据传递给swift 3中的另一个视图控制器?这个函数是在选中一个单元格时,它将从服务器获取JSON数据,然后我必须将JSON数据传递给另一个视图控制器。

func retrieveTime(jobDateValue: String) -> Void {
    if let crew = user!["crew"] as? [String:Any], let crewID = crew["crew_id"] as? String{

        let param = ["action": "retrieve time", "job": ["crew_id": crewID, "jobDate": jobDateValue]] as [String : Any]

        let headers = [
            "content-type": "application/json",
            "cache-control": "no-cache"
        ]

        if let postData = (try? JSONSerialization.data(withJSONObject: param, options: [])) {

            let request = NSMutableURLRequest(url: URL(string: "http://52.221.231.3/gv/app_api.php")!,
                                              cachePolicy: .useProtocolCachePolicy,
                                              timeoutInterval: 10.0)
            request.httpMethod = "POST"
            request.allHTTPHeaderFields = headers
            request.httpBody = postData

            _ = URLSession.shared

            let task = URLSession.shared.dataTask(with: request as URLRequest) {
                    (data, response, error) -> Void in
                DispatchQueue.main.async(execute: {
                    if let json = (try? JSONSerialization.jsonObject(with: data!, options: [.mutableContainers])) as? NSDictionary
                    {
                        let result = json["result"] as? String

                        if (result == "success") {
                            let passValue = json
                        }else{

                        }
                    }
                })
            }

            task.resume()
        }

    }

}

将json数据传递给第二个视图控制器

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "SecondVCSegue"{
        if let destination = segue.destination as? SecondVC {
            destination.passedData = json
        }
    }
}

JSON输出:

{
    jobs =     (
                {
            jobDate = "2017-09-01";
            jobEndTime = 1504231200;
            jobID = 88;
            jobTime = 1504224000;
        }
    );
    message = "Retrieve Sucessfully";
    result = success;
}

1 个答案:

答案 0 :(得分:0)

您应该在Storyboard中设置一个手动segue,您只需在网络请求的完成处理程序内调用。如果segue连接到单个tableview单元格,则在异步函数完成执行之前,系统将调用它。将segue更改为手动且未连接到静态表格视图单元格后,可以使用函数performSegue调用它。

func retrieveTime(jobDateValue: String) -> Void {
    if let crew = user!["crew"] as? [String:Any], let crewID = crew["crew_id"] as? String{
        let param = ["action": "retrieve time", "job": ["crew_id": crewID, "jobDate": jobDateValue]] as [String : Any]
        let headers = [ "content-type": "application/json", "cache-control": "no-cache" ]

        if let postData = (try? JSONSerialization.data(withJSONObject: param, options: [])) {
            var request = URLRequest(url: URL(string: "http://52.221.231.3/gv/app_api.php")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
            request.httpMethod = "POST"
            request.allHTTPHeaderFields = headers
            request.httpBody = postData

            let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in
                guard error == nil, let data = data else {return}
                DispatchQueue.main.async{
                    if let json = (try? JSONSerialization.jsonObject(with: data)) as? [String:Any]{
                        let result = json["result"] as? String
                        if (result == "success") {
                            let passValue = json
                            self.performSegue(withIdentifier: "YourSegue", sender: json)
                        } else{

                        }
                    }
                }
            }
            task.resume()
        }
    }
}

在可用时使用原生Swift对象而不是基础对象(例如NSDictionaryNSMutableURLRequest)。

您还应该使用sender的{​​{1}}选项将performSegue数据发送到其他视图控制器,而不是将其存储在另一个变量中,除非您使用json也是第一个视图控制器中的对象。

json