2017-02-27 43 views
0

我是一般的Swift和iOS編程新手。
目前我正在開發一個應用程序,它會調用API並提取數據並顯示它們。如何在iOS中實現可處理多個API調用的數據模型?

因此,進出口使用GET請求我得到的數據經過獲取的數據,因此,例如,

www.example.com/city1 would give the details of city1 , 
www.example.com/city2 would give the details of city 2 and so on. 

,我分析他們,從中提取JSON必填字段。


我的問題

我有,我有,以顯示不同的城市同樣參數的屏幕。

Ex:我的屏幕2有8個UI標籤,每個標籤都應顯示來自不同城市的相同信息(溫度)。

唯一的變化是我在進行API調用時在GET請求中發送的城市名稱參數。我已經在項目的一個單獨的Swift文件中使用Alamofire實現了GET請求。 那麼實現相同的最好方法是什麼? 我使用Swift 3來處理上述項目。

回答

1
import Alamofire 

struct City { 

    //eight fields 
    let name: String 


    init?(json: [String: Any]) { 
     // init and check required fields 
     if let name = json["name"] as? String { 
      self.name = name 
     } else { 
      return nil 
     } 
    } 

    static func fetchCity(for id: String, success: @escaping (City) -> Void, fail: @escaping (Error?) -> Void) { 
     Alamofire.request("wwww.example.com/\(id)").responseJSON { (response) in 
      if let error = response.error { 
       fail(error) 
      } 

      if let json = response.result.value as? [String: Any] { 
       if let city = City(json: json) { 
        success(city) 
       } 

       //Missing required fields 
       fail(customError) 
      } 
     } 
    } 
} 



City.fetchCity(for: "city1", success: { city in 

}, fail: { error in 

}) 

您可以使用SwiftyJSON用於解析JSON響應

相關問題