swift:How 将base64String编码的图片保存到本地目录

swift:How to save the base64String encoded Image into local directory

我正在尝试将我的照片保存到本地目录中。我使用 UIImagePickerView 控制器使用 Swift。上传图片后,我得到了 base64String 上传图片的响应。

我将它们转换如下:

//encoding
let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String)


//decoding
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))
var decodedimage = UIImage(data: decodedData!)
print(decodedimage)

//Turning base64 encoded string into an NSData
let encodedImageData = base64String
let FinalimageData = NSData(base64EncodedString: encodedImageData, options: [])
print(FinalimageData)

let image = UIImage(data: FinalimageData!)

要求:

I want to save the image to my local directory. How can i do this using Swift 2.

您可以通过以下方式将图片保存到本地目录。使用 fileName.

添加图片扩展
let filePath = "\(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])/\(fileName)"
let imageData : Data = UIImagePNGRepresentation(image)! as Data
 imageData.write(toFile: filePath, atomically: true)
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let fileURL = documentsURL.appendingPathComponent("\(fileName).png")
    if let pngImageData = UIImagePNGRepresentation(image) {
    pngImageData.write(to: fileURL, options: .atomic)
}