xcode 使用 URL 的简单 Swift 文件下载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26408613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple Swift file download with URL
提问by Gio
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 file.
因此,我将 URL 作为字符串(在本例中为 JPG,但如果可能的话,希望任何文件类型的一般程序),并且我将文件路径作为字符串,我想在其中保存文件。
What would be the fastest way to get this implemented?
实现这一目标的最快方法是什么?
Please keep in mind this is for OSX command line application. I tried few sample codes found here, mostly using UIImage but I get error:"Use of unresolved identifier", adding "import UIKit" gets me error:"No such Module". Please help!
请记住,这是针对 OSX 命令行应用程序的。我尝试了一些在这里找到的示例代码,主要是使用 UIImage 但我得到错误:“使用未解析的标识符”,添加“导入 UIKit”得到我的错误:“没有这样的模块”。请帮忙!
import Foundation
let myURLstring = "http://www.safety.vanderbilt.edu/images/staff/Bob-Wheaton.jpg"
let myFilePathString = "/Volumes/HD/Staff Pictures/Bob-VEHS.jpg"
---> ABOVE IS THE ORIGINAL QUESTION <---
---> 以上是原始问题 <---
---> BELOW IS NEW IMPROVED CODE: WORKING <---
---> 下面是新的改进代码: 工作 <---
import Foundation
let myURLstring = "http://www.safety.vanderbilt.edu/images/staff/Bob-Wheaton.jpg"
let myFilePathString = "/Volumes/HD/Staff Pictures/Bob-VEHS.jpg"
let url = NSURL(string: myURLstring)
let imageDataFromURL = NSData(contentsOfURL: url)
let fileManager = NSFileManager.defaultManager()
fileManager.createFileAtPath(myFilePathString, contents: imageDataFromURL, attributes: nil)
采纳答案by Nate Cook
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.
如果你正在编写OS X,你将使用NSImage
替代UIImage
。你需import Cocoa
要这样做 - UIKit 适用于 iOS,Cocoa 适用于 Mac。
NSData
has an initializer that takes a NSURL
, and another that takes a file path, so you can load the data either way.
NSData
有一个带 的初始化程序,NSURL
另一个带文件路径的初始化程序,因此您可以以任何一种方式加载数据。
if let url = NSURL(string: myURLstring) {
let imageDataFromURL = NSData(contentsOfURL: url)
}
let imageDataFromFile = NSData(contentsOfFile: myFilePathString)
回答by OlivierM
With Swift 4, the code will be:
使用Swift 4,代码将是:
if let url = URL(string: myURLstring) {
let imageDataFromURL = try Data(contentsOf: url)
}