我有一个循环,意味着使用Alamofire对Youtube的API进行10次不同的调用,每个调用我从另一个函数获得的视频ID不同。然而,这个电话似乎没有成功,因为我没有从Alamofire交换机的“成功”或“失败”选项中获得结果。
有人可以指出什么是错的吗?
func getRecom(completion: (result:String)->()) {
let array = defaults.arrayForKey("recomQuery")
for i in 0..<10 {
let videoURL = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet&id=\(array![i])&maxResults=10&key=\(apiKey)"
Alamofire.request(.GET, videoURL).validate().responseJSON { response in
switch response.result {
case .Success:
print("success") //THIS IS NOT BEING CALLED
if let value = response.result.value {
let json = JSON(value)
let videoTitle = json["items"][0]["snippet"]["title"].stringValue
print("Title from network \(videoTitle)")
let thumbPath = String(json["items"][0]["snippet"]["thumbnails"]["default"]["url"])
print(i)
let image = UIImage(data: NSData(contentsOfURL: NSURL(string: thumbPath)!)!)!
let newImage: NSData = UIImagePNGRepresentation(image)!
self.recomTitles.append(videoTitle)
self.recomThumbs.append(newImage)
}
case .Failure(let error):
print("failure") //THIS IS ALSO NOT BEING CALLED
print(error)
completion(result: "done")
}
}
}
print("saving array: \(defaults.arrayForKey("recomTitles"))")
defaults.setObject(recomThumbs, forKey: "recomThumbs")
defaults.setObject(recomTitles, forKey: "recomTitles")
completion(result: "done")
}
提前致谢!
答案 0 :(得分:1)
如果 你在Playground中运行它,那么程序可能会在调用打印之前结束,因为你是从异步方法调用它。如果是这种情况,请在开头调用XCPExecutionShouldContinueIndefinitely()。
答案 1 :(得分:0)
谢谢大家!我认为这是一个异步调用,所以在时间之前调用完成,我通过在循环内添加来修复它:
if i == 9 { completion(result: "done") } //9 being the last index of loop
再次感谢!