如何下载swift文件? [英] How to download file in swift?

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

问题描述

我刚刚开始学习iOS的Android的苹果快速编程。我基本上现在可以阅读和操纵swift代码,并且还学习了一些常用的类在iOS快速编程中使用的类,但仍然有一些混淆的语法和一切。



我正在尝试下载文件。喜欢,让我们来说说这个网址来自

  var url =http://www.mywebsite.com/myfile.pdf 

在按钮点击。也许视觉进步也是



通过在stackoverflow中搜索,我偶然发现了Alamofire。我可能会尝试,但我不知道这是否是我最好的方法。



所以,我想问一下我的选择(iOS7和iOS8)实现我的目标。另外,优点和缺点会很棒!

解决方案

不含Alamofire的示例下载器类:

  class Downloader {
class func load(URL:NSURL){
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession (配置:sessionConfig,delegate:nil,delegateQueue:nil)
let request = NSMutableURLRequest(URL:URL)
request.HTTPMethod =GET
let task = session.dataTaskWithRequest(request, completionHandler:{(data:NSData !, response:NSURLResponse !, error:NSError!) - > Void in
if(error == nil){
// Success
let statusCode = (响应为NSHTTPURLResponse).statusCode
println(Success:\(statusCode))

//这是您的文件变量:
// data
}
el se {
// Failure
println(Failure:%@,error.localizedDescription);
}
})
task.resume()
}
}

这是如何在自己的代码中使用它:

  class Foo {
func bar(){
如果var URL = NSURL(string:http://www.mywebsite.com/myfile.pdf){
Downloader.load(URL)
}
}
}

Swift 3版本 / p>

另请注意,在磁盘上下载大型文件而不是在内存中。请参阅`downloadTask:

  class Downloader {
class func load(url:URL,to localUrl:URL,completion: @escaping() - >()){
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration:sessionConfig)
let request = try! URLRequest(url:url,方法:.get)

让task = session.downloadTask(with:request){(tempLocalUrl,response,error)in
如果让tempLocalUrl = tempLocalUrl,error == nil {
// Success
if let statusCode =(response as?HTTPURLResponse)?statusCode {
print(Success:\(statusCode))
}

do {
try FileManager.default.copyItem(at:tempLocalUrl,to:localUrl)
completion()
} catch(let writeError){
打印(错误写入文件\(localUrl):\(writeError))
}

} else {
print(Failure:%@,error ?.localizedDescription);
}
}
task.resume()
}
}


I just started learning apple swift programming for iOS coming from android. I basically can now read and manipulate swift code and also learned some common classes used in iOS swift programming but still having some confusion with the syntax and everything.

I'm trying to download file. Like, lets just say coming from this URL

var url = "http://www.mywebsite.com/myfile.pdf"

in a button click. Maybe with visual progress too

Through searching here in stackoverflow, I stumbled upon Alamofire. I might try it but I'm not sure if this is the best way for me to do it.

So, I would like to ask how and what are my options (iOS7 and iOS8) in achieving my goal. Also, pros and cons would be awesome!

解决方案

Example downloader class without Alamofire:

class Downloader {
    class func load(URL: NSURL) {
        let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
        let request = NSMutableURLRequest(URL: URL)
        request.HTTPMethod = "GET"
        let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
            if (error == nil) {
                // Success
                let statusCode = (response as NSHTTPURLResponse).statusCode
                println("Success: \(statusCode)")

                // This is your file-variable:
                // data
            }
            else {
                // Failure
                println("Failure: %@", error.localizedDescription);
            }
        })
        task.resume()
    }
}

This is how to use it in your own code:

class Foo {
    func bar() {
        if var URL = NSURL(string: "http://www.mywebsite.com/myfile.pdf") {
            Downloader.load(URL)
        }
    }
}

Swift 3 Version

Also note to download large files on disk instead instead in memory. see `downloadTask:

class Downloader {
    class func load(url: URL, to localUrl: URL, completion: @escaping () -> ()) {
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)
        let request = try! URLRequest(url: url, method: .get)

        let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Success: \(statusCode)")
                }

                do {
                    try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl)
                    completion()
                } catch (let writeError) {
                    print("error writing file \(localUrl) : \(writeError)")
                }

            } else {
                print("Failure: %@", error?.localizedDescription);
            }
        }
        task.resume()
    }
}

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

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