我正在努力做到以下几点
我有一个数组,其中包含几个不同图像的URL。这些图像将显示在滚动视图中,我希望保留此顺序,以便能够删除特定索引处的特定图像
现在我正在使用for循环,首先我用NSNull
个对象加载数组,然后我运行循环用图像替换所有对象。这似乎并不真正有效,特别是当应用程序从后台加载时。
这是我的代码:
func downloadImagesfromUrlArray(){
for var i=0;i < graphsURLlist.count; i++ {
if let data = NSData(contentsOfURL: graphsURLlist[i]){
let image = UIImage(data: data)
pageImages.replaceObjectAtIndex(i, withObject: image!)
//self.scaleImagesandScrollView()
}else{
NSLog("%@", i)
var alert = myAlertController(title: nil, message: "Error trying to update the charts. Try again later \(i)",
preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
//Enter queue for every image to download
}
dispatch_group_leave(self.group)
}
有更好的方法吗? 谢谢
答案 0 :(得分:0)
您最好以异步方式下载图像并缓存它们。在下载图像之前,最好显示微调器,然后用图像替换它。
以下是我最新应用中的一些相关方法:
func downloadAndCacheImg(url: String?, cell: AppCell, tableView: UITableView, indexPath: NSIndexPath) {
if url == nil { return }
let charactersToRemove = NSCharacterSet.alphanumericCharacterSet().invertedSet
let cacheFilename = "".join(url!.componentsSeparatedByCharactersInSet(charactersToRemove))
if let fullFilename = prefixFilenameWithDirectory(cacheFilename), img = UIImage(named: fullFilename) {
cell.setAppImage(img)
return
}
if let nsUrl = NSURL(string: url!) {
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: nsUrl), queue: NSOperationQueue.mainQueue(), completionHandler: { (response, data, error) -> Void in
if let data = data, img = UIImage(data: data) {
if let fullFilename = self.prefixFilenameWithDirectory(cacheFilename) {
data.writeToFile(fullFilename, atomically: true)
}
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? AppCell {
cell.setAppImage(img)
}
}
})
}
}
func prefixFilenameWithDirectory(filename: String) -> String? {
var dir = NSFileManager.defaultManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true, error: nil)
dir = dir?.URLByAppendingPathComponent(filename)
return dir?.path
}