2016-02-08 151 views
0

我想添加數據到我的數據模型,以便測試它我正在打印通過Alamofire獲取的信息,但我的問題是因爲一些數據需要再次調用api它變成了空當我打印它。這裏是我的代碼等待多個Alamofire請求

代碼用於獲取個人的數據

func printAPI(){ 

swApiHandler.requestSWPApi("http://swapi.co/api/people", completionHandler: {(response, error) in 

    let json = JSON(response!) 
    let jsonResult = json["results"] 

    for (index,person):(String, JSON) in jsonResult{ 
     let name = person["name"].stringValue 
     let height = person["height"].intValue 
     let mass = person["mass"].intValue 
     let hairColor = person["hair_color"].stringValue 
     let skinColor = person["skin_color"].stringValue 
     let eyeColor = person["eye_color"].stringValue 
     let birthYear = person["birth_year"].stringValue 
     let gender = person["gender"].stringValue 
     let homeWorldUrl = person["homeworld"].stringValue 
     let homeWorldNameKey = "name" 
     let homeWorld = self.getSWApiSpecificValue(homeWorldUrl, strKey: homeWorldNameKey) 

     print("Name: \(name)") 
     print("Height: \(height)") 
     print("Mass: \(mass)") 
     print("Hair Color: \(hairColor)") 
     print("Skin Color: \(skinColor)") 
     print("Eye Color: \(eyeColor)") 
     print("Birth Year: \(birthYear)") 
     print("Gender: \(gender)") 
     print("Home World: \(homeWorld)") 
     print("------------------------------") 
    } 
}) 

} 

代碼用於獲取特定值

func getSWApiSpecificValue(strUrl: String, strKey: String) -> String{ 
    var name = "" 
    swApiHandler.requestSWPApi(strUrl, completionHandler: {(response,error) in 
     let json = JSON(response!) 
     print(json[strKey].stringValue) 
     name = json[strKey].stringValue 
    }) 

    return name 
} 

如果你想知道這裏的JSON模式是

JSON Model

而且在這裏運行代碼的輸出 Output

+0

是什麼問題? –

+0

將斷點放入完成處理程序並返回語句,並嘗試調試該應用程序。 –

+0

@Pooja看看Homeworld的價值是空的,因爲它被異步提取(嵌套的Api調用) –

回答

1

你應該讓你的API調用的背景和它完成填充上主隊列數據之後。 只要改變你的代碼來獲取特定的值這一個:

func getSWApiSpecificValue(strUrl: String, strKey: String) -> String{ 
    var name = "" 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {() -> Void in 
swApiHandler.requestSWPApi(strUrl, completionHandler: {(response,error) in 
    dispatch_async(dispatch_get_main_queue()) { 
     let json = JSON(response!) 
     print(json[strKey].stringValue) 
     name = json[strKey].stringValue 
     return name 
    } 
    }) 
} 
} 

在上面的代碼首先你向服務器請求在background,如果你得到響應在main隊列將填充你variable name。 此外,它是更好地改變你的API調用功能,以類似的東西:

func getDataFromServer(ulr: String, success: (([AnyObject]) -> Void)?, failure: (error: ErrorType) -> Void){ 
} 

通過這種方式可以處理你的錯誤,如果成功,讓您的數據。

+0

哇!很高興你在我的文章中留言。我會明天早上檢查這個代碼,看看它是否工作,順便說一句..謝謝你的建議。這對我的代碼非常有用:D –