带有URL的简单Swift文件下载 [英] Simple Swift file download with URL

查看:87
本文介绍了带有URL的简单Swift文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我将URL作为字符串(在本例中为JPG,但如果可能的话,想要任何文件类型的通用步骤),并且我将文件路径作为字符串,用于保存文件.

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.

实现此目标最快的方法是什么?

What would be the fastest way to get this implemented?

请记住,这是针对OSX命令行应用程序的.我尝试了一些在这里找到的示例代码,主要使用UIImage,但出现错误:使用未解决的标识符",添加导入UIKit"会得到错误:无此类模块".请帮忙!

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!

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)

推荐答案

如果要为OS X编写,则将使用 NSImage 而不是 UIImage .为此,您需要 import Cocoa -UIKit适用于iOS,Cocoa适用于Mac.

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 有一个使用 NSURL 的初始化程序,以及一个使用文件路径的初始化程序,因此您可以以任何一种方式加载数据.

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)

这篇关于带有URL的简单Swift文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆