我正在尝试将vidar附加到videoArray,它只能在Alamofire块中运行。当我试图获得它的计数时,我得到一个返回0但是在Alamofire
块的一侧,我回来了5.我猜它与范围有关?我在getFeedVideos()
内调用了函数viewDidLoad
。
let APIKey = "AIzaSyBF1fGTvY4Z73jNBRFlxiSDelt4zqMnNCg"
var videoArray = [VideoObj]()
// main function
func getFeedVideos (){
// Fetch video data
Alamofire.request(.GET, "https://www.googleapis.com/youtube/v3/playlistItems", parameters: ["part":"snippet", "playlistId": "PL8kma_GjQgWzBLAciqmwC4duAPcSRyt8T", "key":APIKey], encoding: ParameterEncoding.URL, headers: nil).responseJSON { (response) -> Void in
var vidar = [VideoObj]()
if let value = response.result.value {
var arrayofvideos = [VideoObj]()
// loop
for videos in value["items"] as! NSArray {
let videoObject = VideoObj()
videoObject.videoID = videos.valueForKeyPath("snippet.resourceId.videoId") as! String
videoObject.videoTitle = videos.valueForKeyPath("snippet.title") as! String
videoObject.videoDescription = videos.valueForKeyPath("snippet.description") as! String
videoObject.vidoeoThumbUrl = videos.valueForKeyPath("snippet.thumbnails.maxres.url") as! String
arrayofvideos.append(videoObject)
} // For loop ends
//print(arrayofvideos.count) // Prints out 5, which is correct
//print(arrayofvideos[0].videoTitle) // Prints out video title
// P A R S E print("JSON: \(value)")
//
vidar = arrayofvideos
} // If Statement ends
print(vidar.count) // prints 5
self.videoArray = vidar
print(self.videoArray) // prints array
} // AlamoFire Ends
// ** Anything in there returns 0 ** //
print("\(videoArray.count) count ") // But this array prints out 0 !?!?
//print(arrayofvideos[0].videoTitle) // No title "fatal error: Array index out of range"
} // Function End
答案 0 :(得分:0)
是的,这与变量videoArray
的范围有关。 videoArray
的范围是getFeedsVideos()
函数的本地范围。这也是vidar
的情况。要增加这些变量的范围,可以通过在类的顶部声明它们来将它们移动到实例级别。