Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

nsdata - Is there a writeToFile equivalent for Swift 3's 'Data' type?

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

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

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).

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

jpegData.writeToFile(imagePath, atomically: true) 

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use write(to: fileURL).

For example:

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)
}

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)
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...