将HTTP请求中的JSON响应传递给Swift 3中的另一个ViewController

时间:2017-05-09 22:43:43

标签: ios json swift3 httprequest segue

我是iOS的新手,希望有人愿意帮助我解决我遇到的问题

说我的故事板中有2个视图:   - View1:有1个文本框   - View2:有1个标签

每个分别由ViewControllers控制:   - FirstViewController   - SecondViewController

我的应用会将View1中文本框的文本作为HTTP(POST)请求发送到API,并在View2上显示以JSON格式发回的结果。

我的方法是使用prepare(对于segue:,Sender :),但是我很难从Task()返回JSON响应,以便通过Segue将它发送到SecondViewController。

class ResultViewController: UIViewController {


@IBOutlet var text_input: UITextField!

Let api_url = (the api url)

func makeRequest(voucher_number:String, redemption_code:String){

    let json: [String: Any] = [
        "input" : text_input.text
        ]

    let request_json = try? JSONSerialization.data(withJSONObject: json)


    let url:URL = URL(string: api_url)!
    let session = URLSession.shared

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

    request.httpBody = request_json

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (
        data, response, error) in

        guard let _:Data = data, let _:URLResponse = response  , error == nil else {
            return
        }

        let json: Any?

        do
        {
            json = try JSONSerialization.jsonObject(with: data!, options: [])
        }
        catch
        {
        }

        guard let server_response = json as? [String: Any] else
        {
            return
        }

          //This is where I think the return should take place 
          //but can't figure out how

        })

    task.resume()
}

}

我知道我需要通过添加返回语法来修改我的func声明,但我无法弄清楚如何首先返回数据:P所以我暂时跳过这部分。

然后我会执行以下操作将响应发送到SecondViewController

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "firstSegue" {
        if let resultViewController = segue.destination as? SecondViewController {

            if (text_input.text != nil && redemption_code.text != nil) {
               if let json_response = makeRequest() {
            SecondViewController.request_result = json_response
                }
                  // request_result is the variable in 
                  // SecondViewController that will store the data 
                  // being passed via the segue.
            }
        }
    }
}

我知道我的代码可能不是我想要实现的最佳实践。而且我愿意接受建议来解决不同的方法,只要它对我来说不是太先进。

干杯

1 个答案:

答案 0 :(得分:0)

通知是从完成处理程序块中转发JSON数据的好方法,例如:

NotificationCenter.default.post(name: Notification.Name(rawValue:"JSON_RESPONSE_RECEIVED"), object: nil, userInfo: server_response)

在FirstViewController中注册并处理通知:

NotificationCenter.default.addObserver(self, selector: #selector(FirstViewController.json_Response_Received(_:)), name:NSNotification.Name(rawValue: "JSON_RESPONSE_RECEIVED"), object: nil)

(在viewDidLoad()中)和:

func json_Response_Received(_ notification:Notification) {

responseDictionary = (notification as NSNotification).userInfo as! [String:AnyObject];

self.performSegue(withIdentifier: "SegueToSecondController", sender: self)

}

然后你可以将responseDictionary传递给SecondViewController:

    override func prepare(for segue:UIStoryboardSegue, sender:Any?) {

        if (segue.identifier == "SegueToSecondController") {

          secondViewController = segue.destinationViewController as! SecondViewController
          secondViewController.response = responseDictionary 

        }
    }