2017-05-09 35 views
0

我新的iOS和希望有人願意幫助我,我有斯威夫特傳遞JSON響應從HTTP請求到其他的ViewController 3

一個問題,說我有2次我故事板: - 視圖1:有1個文本框中 - 視圖2:有1個標籤

每個分別由一個ViewControllers控制: - FirstViewController - SecondViewController

我的應用程序將發送文本框的文本視圖1作爲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. 
      } 
     } 
    } 
} 

我知道我的代碼可能不是我想要達到的最佳實踐。我願意提出解決不同方法的建議,只要它對我來說不是太先進。

乾杯

+0

沒有必要在這種情況下使用SEGUE。只需在任務的回調方法中呈現/推送新的viewController即可。 – jokeman

回答

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 

     } 
    }