2016-07-27 86 views
1

所以我有一個函數需要返回從API端點接收到的JSON對象。出於某種原因,這個函數總是返回nil,即使當我打印response.result.value時,它完美地包含了API響應,並輸入了要分配給returnJSON的if語句。將不勝感激任何投入!Swift:從函數返回類型JSON

func storeContact(name: String, number: String, apiToken: String) -> AnyObject? { 

var returnJSON: AnyObject? 

let contact = ["api_token" : apiToken, "name" : name, "number": number] 

Alamofire.request(.POST, "http://sample.app/api/v1/contact", parameters: contact, encoding: .JSON).responseJSON { (response) -> Void in 

    if let value = response.result.value { 

     returnJSON = value 

    } 
} 

return returnJSON 

} 
+3

你爲什麼不解析JSON成字典和詞典回報?在從POST請求收到結果之前,您還要返回'returnJSON',因此它是零。使用塊。 – NSNoob

+0

請參閱如何使用[Swift Closures with Alamofire for Network requests](http://stackoverflow.com/questions/25141829/swift-closure-with-alamofire) – NSNoob

回答

2

Alamofire使用異步調用,因爲Internet抓取總是需要一些時間。完成塊Alamofire.request始終調用storeContact返回值。其常見的在這種情況下使用閉包:

func storeContact(name: String, number: String, apiToken: String, completeonClosure: (AnyObject?) ->()) { 
    let contact = ["api_token" : apiToken, "name" : name, "number": number] 

    Alamofire.request(.POST, "http://sample.app/api/v1/contact", parameters: contact, encoding: .JSON).responseJSON { 
     response in 
     completeonClosure(response.result.value) 
    } 
} 

用法:

storeContact("name", number: "number", apiToken: "apiToken") { 
    returnJSON in 
    print(returnJSON) 
} 
+1

傳說,該作品非常值得感謝! – frostfat