2016-11-07 46 views
5
let url = "http://xyz/index_main.php?c=webservices&a=get&e=007" 

    Alamofire.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default) 
     .responseJSON { response in 
      print(response) 
      //to get status code 
      if let status = response.response?.statusCode { 
       switch(status){ 
       case 201: 
        print("example success") 
       default: 
        print("error with response status: \(status)") 
       } 
      } 
      //to get JSON return value 
      if let result = response.result.value { 
       let JSON = result as! NSDictionary 
       print(JSON) 
      } 

結果:無法投類型的值 '__NSArrayI'(0x10df73c08)爲 'NSDictionary中'(0x10df74108)

{ 
    "create_by" = 007; 
    "create_date" = "2016/06/20"; 
    "due_date" = "2016/06/22"; 
    "estimate_time" = ""; 
    fixer = 007; 
    priority = High; 
    "project_code" = testing; 
    status = "Re-Open"; 
    "task_id" = 228; 
    "task_title" = test; 
    tester = 007; 
}, 
    { 
    "create_by" = 006; 
    "create_date" = "2016/06/23"; 
    "due_date" = "2016/06/24"; 
    "estimate_time" = ""; 
    fixer = 007; 
    priority = Critical; 
    "project_code" = "tanteida.c"; 
    status = "In Progress"; 
    "task_id" = 234; 
    "task_title" = testing; 
    tester = 006; 
} 

我要轉換爲NSDictionary,並得到不同的陣列狀task_id(陣列),但我得到這個錯誤:

"Could not cast value of type '__NSArrayI' to NSDictionary"

請幫我

預先感謝您

+2

你的結果是數組......不是字典 –

+0

是的,但我想在字典 – seggy

+0

你到底在陣列中想要什麼? – mttrb

回答

9

你的反應是不DictionaryArrayDictionary,所以如果你想要的所有詞典中,你可以使用循環訪問它。

if let array = response.result.value as? [[String: Any]] { 
    //If you want array of task id you can try like 
    let taskArray = array.flatMap { $0["task_id"] as? String } 
    print(taskArray) 
} 
+0

不同的數組打印這個值到表中。我可以使用taskArray作爲全局變量嗎? – seggy

+0

爲此,您需要將taskArray聲明爲Controller的實例變量。 –

+0

即時新的所以請告訴我我如何宣佈這樣var taskArray =數組()但我知道這是不對的 – seggy

2

這是因爲你的服務以數組的形式返回結果。你需要做的是將結果投給NSArray。然後你就可以通過索引來訪問不同的結果:

let JSON = result as! NSArray 
let firstResult = results[0] 
相關問題