Simple Swift file download with URL

前端 未结 2 1269
暗喜
暗喜 2021-02-10 01:25

So I have the URL as string (in this case a JPG but would like a general procedure for any file type if possible) and I have the file path as string where I want to save the fil

相关标签:
2条回答
  • 2021-02-10 01:53

    With Swift 4, the code will be:

    if let url = URL(string: myURLstring) {
        let imageDataFromURL = try Data(contentsOf: url)
    }
    
    0 讨论(0)
  • 2021-02-10 02:08

    If you're writing for OS X, you'll use NSImage instead of UIImage. You'll need import Cocoa for that - UIKit is for iOS, Cocoa is for the Mac.

    NSData has an initializer that takes a NSURL, and another that takes a file path, so you can load the data either way.

    if let url = NSURL(string: myURLstring) {
        let imageDataFromURL = NSData(contentsOfURL: url)
    }
    
    let imageDataFromFile = NSData(contentsOfFile: myFilePathString)
    
    0 讨论(0)
提交回复
热议问题