2016-11-15 53 views
1

我加載到我的應用程序的API:JSON下載但沒有添加到UITable,但沒有錯誤?

https://wger.de/api/v2/exercise/?language=2

我在我運行Get數據功能表視圖上的API調用沒有錯誤,沒有錯誤。它的工作以前完美直到現在。我沒有改變任何代碼。

我認爲服務器會在通話中關閉,但它們並不像您所看到的那樣。

我正在運行打印'請求成功',它在運行時顯示在調試中,所以它獲取數據,但print(self.exercises)返回一個空數組,因此沒有表數據...任何想法?這裏是API調用

open class ApiService: NSObject { 

    open func getData(completionHandler: @escaping (NSDictionary?, NSError?) -> Void) -> Self { 

     //loads api filtering by english only 
     let requestUrl = "https://wger.de/api/v2/exercise/?format=json&language=2" 

     Alamofire.request(requestUrl, method: .get, encoding: URLEncoding.default) 
      .responseJSON { response in 
       switch response.result { 
       case .success(let data): 
        print("Request was sucessful") 
        completionHandler(data as? NSDictionary, nil) 

       case .failure(let error): 
        print("Request failed with error: \(error)") 
        completionHandler(nil, error as NSError?) 
       } 
     } 
     return self 
    } 

表函數

 func getApiData() { 

    let _ = apiService.getData() { 
     (data, error) in 
     if let data = data { 
      if let results = data["results"] as? [[String:Any]] { 
       for result in results { 
        if let exercise = Exercise(dictionary: result) { 
         self.exercises.append(exercise) 
        } 
       } 
       self.exercisesTableView.reloadData() 
       print(self.exercises) 
      } 
     } 
    } 
} 

我也使用序列化模型,如果能夠干擾?

final public class Exercise { 
var id: Int 
var descrip: String 
var name: String 
var language: [Int] 
var muscles: [Int] 
var musclesSecondary: [Int] 
var equipment: [Int] 

public init?(dictionary: [String: Any]) { 

    guard 
     let id = dictionary["id"] as? Int, 
     let descrip = dictionary["description"] as? String, 
     let name = dictionary["name"] as? String, 
     let language = dictionary["language"] as? [Int], 
     let muscles = dictionary["muscles"] as? [Int], 
     let musclesSecondary = dictionary["muscles_secondary"] as? [Int], 
     let equipment = dictionary["equipment"] as? [Int] 
    else { return nil } 

    self.id = id 
    self.descrip = descrip 
    self.name = name 
    self.language = language 
    self.muscles = muscles 
    self.musclesSecondary = musclesSecondary 
    self.equipment = equipment 
} 
+0

你有沒有設置你的tableView.datasource屬性?或者你在使用UITableVIewController嗎?你的tableView數據源委託函數是從self.excercises中讀取數據的嗎?這裏沒有足夠的信息 – Scriptable

+0

你說'print(self.exercises)'打印一個空數組。難道你創作的「鍛鍊」元素失敗了嗎?嘗試在內部添加一個'print'來得到結果'和另一個'如果讓運動=運動(字典:結果)'看看這些是否被執行 – pbodsk

+0

@vadian是正確的,我的錯誤,儘管我確信這個問題發生了在我擴展序列化之前,我一定是錯了,謝謝你的解決方案,如果你想發佈它作爲答案,我可以標記,否則我只是刪除問題 – infernouk

回答

2

對不起,

I havent changed any code

是錯誤的。

您添加了屬性musclesSecondarylanguage並且確切存在錯誤:language是單個Int而不是數組。

var language: Int 
... 
let language = dictionary["language"] as? Int, 
相關問題