我在尝试将数据访问包含某些图像URL的数组时遇到问题。
每次尝试创建映像时,我的应用程序都不会停止加载,并进行循环,顺便说一下,我的数组也不会停止填充。
这是我的代码:
class swipe : UIViewController, KinderDelegate {
var urls = [NSURL!]()
var pictureApp: String!
func fetchdata(int: Int, completion: (()->())?) {
for repo in repo {
urls.append(NSURL(string: repo.picture_url!)!)
dump(repos)
i++
NSLog("nombre de line = %i", PicArray.count)
pictureApp = repo.picture_url
}
if let img = imageCache[pictureApp!] {
let newCard = Model()
newCard.image = img
print("image présente")
}else {
for url in urls{
if #available(iOS 8.0, *) {
let newCard = Model()
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) {
if let data = NSData(contentsOfURL: url) {
let image = UIImage(data: data)!
newCard.image = (image: image)
dispatch_async(dispatch_get_main_queue()) {
newCard.image
}
}
}
self.data.append(newCard)
}
}
}
if self.data.count == 4 {
completion!()
return
} else {
self.fetchData(0, completion: completion)
}
}
}
如何利用数组中的URL创建一些图像?
最佳答案
像Azzaknight所建议的那样,我尝试了“ repo for repos”循环,并为此更改了代码:
do {
data = try NSData(contentsOfURL: NSURL(string: repo.picture_url!)!, options: NSDataReadingOptions.DataReadingMappedIfSafe)
let image = UIImage(data: data!)!
newCard.image = (image: image)
dispatch_async(dispatch_get_main_queue()) {
newCard.image
}
}
catch {
print("Handle \(error) here")
}
}
}
self.data.append(newCard)
}
现在一切正常!