Swift 3 的“数据"类型是否有等效的 writeToFile? [英] Is there a writeToFile equivalent for Swift 3's 'Data' type?

查看:22
本文介绍了Swift 3 的“数据"类型是否有等效的 writeToFile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以返回新的 iOS 10/Swift 3 NSData 替换(?)类型:数据

I've some code which returns the new iOS 10 / Swift 3 NSData replacement(?) type: Data

if let jpegData = UIImageJPEGRepresentation(newImage, 0.8) { ... }

我想将此图像写入磁盘,但是 NSData 的 writeToFile: 方法不存在于此类中.它确实有一个 writeToURL: 方法,但这似乎不适用于文件路径(和附加组件).

I want to write this image to disk, however NSData's writeToFile: method is not present for this class. It does have a writeToURL: method, but that doesn't seem to work with a file path (and appending component).

任何人都可以澄清我现在将如何执行此操作,就像 Swift 2 中的情况一样:

Can anyone clarify how I would now do this, as used to be the case in Swift 2:

jpegData.writeToFile(imagePath, atomically: true) 

谢谢!

推荐答案

使用 write(to: fileURL).

例如:

let fileURL = try! FileManager.default
    .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    .appendingPathComponent("test.jpg")

do {
    try jpegData.write(to: fileURL, options: .atomic)
} catch {
    print(error)
}

或者,如果您真的被path所困扰,请将其转换为URL:

Or, if you really are stuck with a path, convert that to a URL:

do {
    try data.write(to: URL(fileURLWithPath: path), options: .atomic)
} catch {
    print(error)
}

但是,现在通常最好在整个代码中使用 URL 引用,不再使用路径字符串.

But, generally, it's preferable to use URL references throughout your code nowadays, retiring the use of path strings.

这篇关于Swift 3 的“数据"类型是否有等效的 writeToFile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆