我试图用
Swift显示和保存图像.在第一击中,它在imageview上显示远程图像,第二次按下它会显示空白的imageview,而不是应该是第一次保存的本地图像.
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] as String
var imagePath = paths.stringByAppendingPathComponent("images/\(id)/logo.jpg" )
var checkImage = NSFileManager.defaultManager()
if (checkImage.fileExistsAtPath(imagePath)) {
let getimage = UIImage(contentsOfFile: imagePath)
self.image?.image = getimage
} else {
dispatch_async(dispatch_get_main_queue()) {
let getimage = UIImage(data: NSData(contentsOfURL: NSURL(string: remoteImage)))
UIImageJPEGRepresentation(getimage,100).writetoFile(imagePath,atomically: true)
self.image?.image = getimage
}
}
编辑:这一个为我工作.
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,true)[0] as String
var dirPath = paths.stringByAppendingPathComponent("images/\(id)" )
var imagePath = paths.stringByAppendingPathComponent("images/\(id)/logo.jpg" )
var checkImage = NSFileManager.defaultManager()
if (checkImage.fileExistsAtPath(imagePath)) {
let getimage = UIImage(contentsOfFile: imagePath)
self.image?.image = getimage
} else {
dispatch_async(dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_BACKGROUND,0)) {
checkImage.createDirectoryAtPath(dirPath,withIntermediateDirectories: true,attributes: nil,error: nil)
let getimage = UIImage(data: NSData(contentsOfURL: NSURL(string: remoteImage)))
UIImageJPEGRepresentation(getimage,atomically: true)
dispatch_async(dispatch_get_main_queue()) {
self.image?.image = getimage
return
}
}
}
解决方法
要回答你的主要问题,你打电话给错误的UIImage初始化程序.您应该在swift 2中调用UIImage(contentsOfFile:imagePath),并在swift 3中调用UIImage(contentsOf:imagePath).
另外,看起来您正在使用dispatch_async(或swift 3中的dispatchQueue)在后台进行远程抓取,但是您将其传递给主队列,因此您实际上阻止了主/ .您应该将其分派到其中一个后台队列,然后在实际在UI中设置图像时将其分派回主队列:
Swift 3:
dispatchQueue.global(qos: dispatchQoS.background.qosClass).async {
do {
let data = try Data(contentsOf: URL(string: self.remoteImage)!)
let getimage = UIImage(data: data)
try UIImageJPEGRepresentation(getimage!,100)?.write(to: imagePath)
dispatchQueue.main.async {
self.image?.image = getimage
return
}
}
catch {
return
}
}
Swift 2:
dispatch_async(dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_BACKGROUND,0)) {
let getimage = UIImage(data: NSData(contentsOfURL: NSURL(string: self.remoteImage)))
UIImageJPEGRepresentation(getimage,atomically: true)
dispatch_async(dispatch_get_main_queue()) {
self.image?.image = getimage
return
}
}
@Rob’s answer re:获取远程图像并保存它真的是最好的方法.