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

查看:87
本文介绍了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天全站免登陆