如何通过swift保存和加载文件图像

时间:2015-11-13 09:51:11

标签: uiimage swift2

我有UIImage(来自Parse - 转换变量PFFile)。 如何从此变量中保存和加载图像?

  let a = object["image"] as! PFFile
  a.getDataInBackgroundWithBlock({ (data:NSData?, error:NSError?) -> Void in
      if (error == nil) {
           // I have image, but the next I don't know what I do
           let image = UIImage(data:data!)
      }
   })

1 个答案:

答案 0 :(得分:1)

保存图片

 func saveImage(image:UIImage,name:String){        
     let selectedImage: UIImage = image
     let data:NSData = UIImagePNGRepresentation(selectedImage)
     let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String

     let success = fileManager.createFileAtPath(path, contents: data, attributes: nil)
     print(success)
     // Check image saved successfully
     let getImagePath = (path as NSString).stringByAppendingPathComponent(name)
     if fileManager.fileExistsAtPath(getImagePath) {
        // image save success
        let image = UIImage(contentsOfFile: getImagePath)!
     }
     else{
        // image save error
     }
}

保存其他文件

static func saveFile(fileData:NSData,name:String)->Bool{
    let success = NSFileManager.defaultManager().createFileAtPath(path+"/"+name, contents: fileData, attributes: nil)
    return success
}