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

前端 未结 1 927
名媛妹妹
名媛妹妹 2020-12-13 17:25

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

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


        
相关标签:
1条回答
  • 2020-12-13 18:08

    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.

    0 讨论(0)
提交回复
热议问题