【问题标题】:Passing JSON Response From HTTP Request to Another ViewController in Swift 3在 Swift 3 中将 JSON 响应从 HTTP 请求传递到另一个 ViewController
【发布时间】:2017-05-09 22:43:42
【问题描述】:

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

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

每个都分别由一个 ViewControllers 控制: - 第一视图控制器 - 第二视图控制器

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

我的方法是使用 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()
}

}

我知道我需要通过添加返回语法来修改我的 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.
            }
        }
    }
}

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

干杯

【问题讨论】:

  • 这种情况下不需要使用segue。只需在任务的回调方法中展示/推送您的新 viewController。

标签: ios json swift3 httprequest segue


【解决方案1】:

通知是将 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 

        }
    }

【讨论】:

    猜你喜欢
    • 2014-07-25
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多