我试图用
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:获取远程图像并保存它真的是最好的方法.