简体   繁体   English

在Swift 3中将JSON响应从HTTP请求传递到另一个ViewController

[英]Passing JSON Response From HTTP Request to Another ViewController in Swift 3

I'm new to iOS and was hoping someone would be willing to help me out with an issue I'm having 我是iOS的新手,希望有人愿意为我遇到的问题提供帮助

Say I have 2 Views in my storyboard: - View1: Has 1 text box - View2: Has 1 Label 假设我的故事板上有2个视图:-视图1:具有1个文本框-视图2:具有1个标签

Each being respectively controlled by a ViewControllers: - FirstViewController - SecondViewController 每个分别由一个ViewControllers控制:-FirstViewController-SecondViewController

My app would send the text of the textbox in View1 as an HTTP (POST) request to an API, and would display on View2 the result which is sent back in JSON format. 我的应用程序将通过HTTP(POST)请求将View1中文本框的文本发送到API,并在View2上显示以JSON格式发送回的结果。

My approach is to use the prepare(for segue:,Sender:), however I am having a hard time returning the JSON response from Task() in order to send it to SecondViewController via a Segue. 我的方法是使用prepare(for 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()
}

} }

I know I would need to modify my func declaration by adding the return syntax, but I can't figure out how to return data in the first place :P so I skipped this part for the time being. 我知道我需要通过添加return语法来修改func声明,但是我无法弄清楚如何首先返回数据:P,所以我暂时跳过了这一部分。

I would then do the following to send the response to SecondViewController 然后,我将执行以下操作以将响应发送到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.
            }
        }
    }
}

I know my code may not be the best practice for what I'm trying to achieve. 我知道我的代码可能不是我要实现的最佳实践。 And I'm open to suggestions to tackle a different approach, as long as it's not too advanced for me. 我愿意提出解决另一种方法的建议,只要这对我来说不太高级。

Cheers 干杯

Notifications are a good way to forward JSON data out of completion handler blocks, like: 通知是从完成处理程序块中转发JSON数据的好方法,例如:

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

Register and handle the notification in FirstViewController: 在FirstViewController中注册并处理通知:

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

(in viewDidLoad() ) and: (在viewDidLoad() )和:

func json_Response_Received(_ notification:Notification) {

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

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

}

Then you can pass responseDictionary to SecondViewController in: 然后,您可以通过以下方式将responseDictionary传递给SecondViewController:

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

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

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

        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从JSON中提取值并传递到Swift中的另一个ViewController - Extracting value from JSON and passing to another ViewController in Swift 将一个ViewController中的managedObjectContext传递给Swift中的另一个ViewController? - Passing an managedObjectContext from one ViewController to another ViewController in Swift? Swift:将数据从ViewController中的tableView传递到另一个ViewController - Swift: Passing data from a tableView in a ViewController to another ViewController 将对象从一个ViewController传递到另一个ViewController很快就无效了 - Passing an object from one viewcontroller to another viewcontroller got nil in swift 将Json响应从一个Viewcontroller传递到另一个Viewcontroller并填充CollectionView - Pass Json response from one Viewcontroller to another Viewcontroller and populate CollectionView 在 Swift 中将数据传递给另一个 ViewController - Passing data to another ViewController in Swift 快速将数组值从一个ViewController传递到另一个ViewController - Swift passing array values from one viewcontroller to another 使用Swift将信息从ViewController传递到ViewController - Passing Information from ViewController to ViewController using Swift Swift:将数据从tableView显示到另一个ViewController(JSON,Alamorife,AlamofireImage) - Swift: Show data from tableView to another ViewController (JSON, Alamorife, AlamofireImage) 如何从ViewController访问Swift 3中的另一个viewController - How to access from viewController another viewController in Swift 3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM