我有一个循环,旨在使用Alamofire对Youtube的API进行10次不同的调用,每个调用都有一个我从另一个函数获得的不同videoID。但是,似乎没有进行调用,因为我没有从 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")
}
提前感谢!
如果在 Playground 中运行它,则程序很可能在调用打印之前结束,因为您从异步方法调用它。如果是这种情况,请在开头调用 XCPExecutionShouldContinueIndefinitely()。
谢谢大家!我认为这是一个异步调用,因此在时间之前调用了完成,我通过在循环中添加来修复它:
if i == 9 { completion(result: "done") } //9 being the last index of loop
再次感谢!