2017-04-12 209 views
-1

我用這Alamofire請求並返回一個JSONAlamofire請求響應?

let todoEndpoint: String = "https://api.abc.com/api/v3/products?pid=uid8225&format=json&&offset=0&limit=10" 
    Alamofire.request(todoEndpoint) 
     .responseJSON { response in 
      guard let json = response.result.value as? [String: Any] else { 
       print("didn't get todo object as JSON from API") 
       print("Error: \(response.result.error)") 
       return 
      } 
      print(json) 

} 

現在我有做的循環,我想用這個JSON的價值,但我得到:

錯誤:使用未解決的標識符的JSON ?

do { 

     for (index,subJson):(String, JSON) in json { 

print("Index :\(index) Title: \(subJson)") 

} catch 
{ 

      print("there was an error") 

} 

如前所述:

https://github.com/Alamofire/Alamofire#response-string-handler 「的請求的結果是唯一的響應蓋的範圍內可在響應或數據的任何執行隊伍從服務器接收到必須做在答覆結束之內「。

如何在響應關閉範圍外使用此json值?

能否請你建議

有沒有完成處理程序,我需要寫和怎麼能做到呢?

感謝

+0

[使用新的Swift 3和Alamofire解析JSON](http://stackoverflow.com/questions/39468516/parsing-json-using-the-new-swift-3-and-alamofire) – 2017-04-12 12:13:50

+0

GS ,您是否嘗試搜索解決方案,因爲此問題已被詢問爲超過30多個主題:https://www.google.se/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q= alamofire + json + response + swift + stackoverflow – 2017-04-12 12:14:35

+1

你應該在後衛後面跑,即'guard let else {...} HERE'。目前你在'json'不存在的範圍內執行它 – Honey

回答

1

更好地利用SwiftyJson方便JSON與Almofire解析像波紋管:

import Alamofire 
import SwiftyJSON 

static func getRequest(urlString: URL?, Parameter:NSDictionary?, completion: @escaping (_ serverResponse: AnyObject?,_ error:NSError?)->()){ 

     Alamofire.request(urlString!, parameters:nil, headers: nil).responseJSON { response in 

      if(response.result.value != nil){ 
       let serverResponse = JSON(response.result.value!) 
       print("Array value is \(serverResponse.arrayValue)") 


        completion(serverResponse as AnyObject?, nil) 
      } 
      else{ 
       completion(nil, response.result.error as NSError?) 
      } 
     } 

    } 

你可以像NetworkLayer一個單獨的類寫這個函數,然後從任何類調用它爲WebService呼叫如下:

let url = NSURL(string: yourWebServiceUrlString) 
     NetworkLayer.getRequest(urlString: url as URL?, Parameter: nil) { (serverResponse, error) in 

      if (error == nil){ 
      print("Server response: \(serverResponse)") 
      } 
     } 

注意:您也可以傳遞參數字典。

+1

避免應答以前多次詢問過的重複。 – 2017-04-12 12:15:37

+1

好的,我會關心這一點。 – Aashish1aug

+0

嗨偷偷摸摸,這個問題有點不同於你已經提到的線程,因爲我通過鏈接搜索,但無法得到答案 –