ios - 如何在 swift 3.0 中将图像写入路径

标签 ios swift core-data

我正在使用核心数据来存储从图像选择器中获取的图像的 url。

到目前为止,我有以下内容:

    let tempImage = info[UIImagePickerControllerOriginalImage] as? UIImage

    let image = UIImageJPEGRepresentation(tempImage!, 0.2)

    let path = try! FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: false)
    let imageName = UUID().uuidString + ".jpg"

    let aPath = path.path

    let imagePath = (aPath as NSString).appendingPathComponent(imageName)

结果是现在我有一个字符串形式的路径来保存在核心数据中。 但是如何将图像写入路径? 我试图使用:

   let result = image!.writeToFile(path, atomically: true)

但我收到一条错误消息,指出类型数据的值没有成员 writeToFile。在 swift 3.0 中还有其他方法吗?

感谢您的帮助。

最佳答案

在 Swift 3 中,UIImageJPEGRepresentation 创建 Data 而不是 NSData。您可以使用 write 而不是 writeToFile

您应该能够使用:

image.write(to: URL(fileURLWithPath: path), options: .atomic)

并将图像数据image 写入path 中的文件。请注意,它使用 URL 而不是字符串文件路径,并且选项参数已更改。

关于ios - 如何在 swift 3.0 中将图像写入路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39584626/

相关文章:

ios - iOS 堆栈 View 中水平居中 View

swift - NSFetchedResultsController 谓词消除多个属性的重复项

ios - 如何让 tableView.reloadData() 与核心数据正常工作?

ios - iOS应用程序审核流程: Is gifting access to functionality a violation of the guidelines?

iOS - 无法在 bundle 中加载 NIB

ios - 如何将 NSValue 转换为 CLLocationCoordinate2D

ios - 使用带云代码的 Stripe + Parse 存储信用卡

iOS 5 - 连接到 HTTPS 服务器

ios - UISearchController 搜索两个数组

ios - 当管理对象上下文从持久性存储中加载数据时