让我先谢谢。无论如何,我不明白为什么我的print()
说函数结果正确。但是当我在viewDidLoad()
中调用它时,应该返回的array.count是= 0。
这是我的职能:
import Foundation
import Alamofire
class FetchObjectsFromUrl {
static var sharedInstance = FetchObjectsFromUrl()
func fetchObject() -> [Track]{
let url = "https://itunes.apple.com/search?*****"
var tracks = [Track]()
Alamofire.request(url).responseJSON { (response) in
if let data = response.data {
do {
let decoder = JSONDecoder()
let results = try decoder.decode(Results.self, from: data)
guard let resultTracks = results.results else {return}
for i in resultTracks {
let track = i
tracks.append(track)
print(tracks.count)
}
} catch let err {
print("Unable to decode json", err)
}
}
}
return tracks
}
}
所以我基本上是将其设为全局变量和结果。现在在中间的深处,您将看到一个print()。该打印给出了正确的结果,当我将鼠标悬停在返回变量上时,它也会产生结果。
这是我的viewDidLoad():
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(MainScreenCollectionViewCell.self, forCellWithReuseIdentifier: cellId)
setupViews()
self.tracks = FetchObjectsFromUrl.sharedInstance.fetchObject()
print(tracks.count)
let realmTracks = TracksViewModel.sharedInstance.assiningObjectToRealmObject(tracks)
for track in realmTracks {
CacheManager.sharedInstance.addData(object: track)
}
self.trackList = CacheManager.sharedInstance.getDataFromDB()
}
print()
下方的self.tracks = FetchObjectsFromUrl.sharedInstance.fetchObject()
。请帮助我。