2017-06-15 71 views
0

我要将图像保存到iphone设备并从中读取。 所以我写了这样的函数。如何将图像保存到iPhone设备存储器或从中读取图像?

/* 
* save image to local device 
*/ 
func saveImageToLocal(image: UIImage, fileName: String) { 
    if let data = UIImagePNGRepresentation(image) { 
     let filePath = self.getDocumentsDirectory().appendingPathComponent(fileName) 
     try? data.write(to: filePath, options: .atomic) 
    } 
} 

/* 
* get image from local device 
*/ 
func getImageFromLocal(fileName:String) -> UIImage? { 
    if let filePath = "\(self.getDocumentsDirectory())\(fileName)" as String! { 
     if let image = UIImage(contentsOfFile: filePath) { 
      return image 
     } 
    } 
    return nil 
} 

/* 
* get document directory to save/read local file 
*/ 
func getDocumentsDirectory() -> URL { 
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) 
    let documentsDirectory = paths[0] 
    return documentsDirectory 
} 

但它没有正常工作。 我有这个错误吗? 我该如何执行此操作? 此致敬礼。

+0

为什么'filePath'在保存和获取方法中创建方式如此不同?更新get方法以像在保存方法中那样创建它。 – rmaddy

+0

谢谢!你的帮助非常好。 – LoveCode

回答

0

您在getImageFromLocal(fileName:) -> UIImage?方法中获得filePath时遇到问题。根据您的saveImageToLocal(image:)方法更改此方法,如下所示:

func getImageFromLocal(fileName:String) -> UIImage? { 
    let filePath = self.getDocumentsDirectory().appendingPathComponent(fileName) 
    if let image = UIImage(contentsOfFile: filePath.path) { 
     return image 
    } 
    return nil 
} 
+0

谢谢!它运作良好。 – LoveCode