Swift - 使用URLSession加載數(shù)據(jù)、下載、上傳文件?

原文出自:www.hangge.com 轉(zhuǎn)載請(qǐng)保留原文鏈接:http://www.hangge.com/blog/cache/detail_780.html

URLSession 類支持三種類型的任務(wù):加載數(shù)據(jù)、下載和上傳。下面通過樣例分別進(jìn)行介紹。(本文代碼已升級(jí)至 Swift3)

1,使用Data Task加載數(shù)據(jù)
使用全局的 URLSession.shared 和 dataTask 方法創(chuàng)建。

func sessionLoadData(){
//創(chuàng)建URL對(duì)象
let urlString = "http://hangge.com"
let url = URL(string:urlString)
//創(chuàng)建請(qǐng)求對(duì)象
let request = URLRequest(url: url!)

let session = URLSession.shared
let dataTask = session.dataTask(with: request,
    completionHandler: {(data, response, error) -> Void in
        if error != nil{
            print(error.debugDescription)
        }else{
            let str = String(data: data!, encoding: String.Encoding.utf8)
            print(str)
        }
}) as URLSessionTask

  //使用resume方法啟動(dòng)任務(wù)
  dataTask.resume()
}

2,使用Download Task來下載文件
(1)不需要獲取進(jìn)度
使用全局的 URLSession.shared 和 downloadTask 方法即可

func sessionSimpleDownload(){
//下載地址
let url = URL(string: "http://hangge.com/blog/images/logo.png")
//請(qǐng)求
let request = URLRequest(url: url!)


let session = URLSession.shared
//下載任務(wù)
let downloadTask = session.downloadTask(with: request,
       completionHandler: { (location:URL?, response:URLResponse?, error:Error?)
        -> Void in
        //輸出下載文件原來的存放目錄
        print("location:\(location)")
        //location位置轉(zhuǎn)換
        let locationPath = location!.path
        //拷貝到用戶目錄
        let documnets:String = NSHomeDirectory() + "/Documents/1.png"
        //創(chuàng)建文件管理器
        let fileManager = FileManager.default
        try! fileManager.moveItem(atPath: locationPath, toPath: documnets)
        print("new location:\(documnets)")
})


    //使用resume方法啟動(dòng)任務(wù)
    downloadTask.resume()
}

(2)實(shí)時(shí)獲取進(jìn)度
需要使用自定義的 URLSession 對(duì)象和 downloadTask 方法

import UIKit

class ViewController: UIViewController, URLSessionDownloadDelegate {


private lazy var session:URLSession = {
    //只執(zhí)行一次
    let config = URLSessionConfiguration.default
    let currentSession = URLSession(configuration: config, delegate: self,
                                    delegateQueue: nil)
    return currentSession

}()


override func viewDidLoad() {
    super.viewDidLoad()


    sessionSeniorDownload()
}


//下載文件
func sessionSeniorDownload(){
    //下載地址
    let url = URL(string: "http://hangge.com/blog/images/logo.png")
    //請(qǐng)求
    let request = URLRequest(url: url!)


    //下載任務(wù)
    let downloadTask = session.downloadTask(with: request)


    //使用resume方法啟動(dòng)任務(wù)
    downloadTask.resume()
}



//下載代理方法,下載結(jié)束
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
                didFinishDownloadingTo location: URL) {
    //下載結(jié)束
    print("下載結(jié)束")


    //輸出下載文件原來的存放目錄
    print("location:\(location)")
    //location位置轉(zhuǎn)換
    let locationPath = location.path
    //拷貝到用戶目錄
    let documnets:String = NSHomeDirectory() + "/Documents/2.png"
    //創(chuàng)建文件管理器
    let fileManager = FileManager.default
    try! fileManager.moveItem(atPath: locationPath, toPath: documnets)
    print("new location:\(documnets)")
}


//下載代理方法,監(jiān)聽下載進(jìn)度
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
                didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
                totalBytesExpectedToWrite: Int64) {
    //獲取進(jìn)度
    let written:CGFloat = (CGFloat)(totalBytesWritten)
    let total:CGFloat = (CGFloat)(totalBytesExpectedToWrite)
    let pro:CGFloat = written/total
    print("下載進(jìn)度:\(pro)")
}


//下載代理方法,下載偏移
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
                didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
    //下載偏移,主要用于暫停續(xù)傳
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

3,使用Upload Task來上傳文件

func sessionUpload(){
//上傳地址
let url = URL(string: "http://hangge.com/upload.php")
//請(qǐng)求
var request = URLRequest(url: url!, cachePolicy: .reloadIgnoringCacheData)
request.httpMethod = "POST"


let session = URLSession.shared


//上傳數(shù)據(jù)流
let documents =  NSHomeDirectory() + "/Documents/1.png"
let imgData = try! Data(contentsOf: URL(fileURLWithPath: documents))

let uploadTask = session.uploadTask(with: request, from: imgData) {
    (data:Data?, response:URLResponse?, error:Error?) -> Void in
    //上傳完畢后
    if error != nil{
        print(error)
    }else{
        let str = String(data: data!, encoding: String.Encoding.utf8)
        print("上傳完畢:\(str)")
    }
}

  //使用resume方法啟動(dòng)任務(wù)
  uploadTask.resume()
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容