URLSession

Get请求

func httpGet() {

    let url = URL(string:"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON")

    let request = URLRequest(url: url!)

    let session = URLSession.shared

    let task = session.dataTask(with: request) { (data:Data?, response:URLResponse?, error:Error?) in

        print(data!)
        print(response!)
        let resultStr = String.init(data: data!, encoding: String.Encoding.utf8)

        print(resultStr!)

        let result:[String:Any] = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : Any]

        print(result["success"]!)
    }

    task.resume()
}

Post请求

func httpPost() {

    let url = URL(string: "http://120.25.226.186:32812/login?")
    var request = URLRequest.init(url: url!)
    request.httpMethod = "POST"
    request.httpBody = "username=520it&pwd=520it&type=JSON".data(using: .utf8)

    let session = URLSession.shared

    let task = session.dataTask(with: request) { (data:Data?, response:URLResponse?, error:Error?) in

        print(data!)
        print(response!)
        let resultStr = String.init(data: data!, encoding: String.Encoding.utf8)

        print(resultStr!)

        let result:[String:Any] = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : Any]

        print(result["success"]!)
    }
}

使用代理获取响应数据

func httpPost() {

    let url = URL(string: "http://120.25.226.186:32812/login?")
    var request = URLRequest.init(url: url!)
    request.httpMethod = "POST"
    request.httpBody = "username=520it&pwd=520it&type=JSON".data(using: .utf8)

    //遵守协议
    let session = URLSession.init(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.init())

    let task = session.dataTask(with: request)
    task.resume()
}
extension ViewController : URLSessionDataDelegate {
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        let resultStr = String.init(data: data, encoding: String.Encoding.utf8)

        print(resultStr!)

        let result:[String:Any] = try! JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : Any]

        print(result["success"]!)
    }
}

下载

小文件下载

func download() {

    guard let url = URL(string: "http://120.25.226.186:32812/resources/images/minion_01.png") else {
        return
    }
    let request = URLRequest(url: url)

    let session = URLSession.shared

    let task = session.downloadTask(with: request) { (location:URL?, respose:URLResponse?, error:Error?) in

        //如果不指定存储目录,下载的数据会被当做是一个临时对象缓存在tmp目录下,随时可能被系统清理

        //所以我们要重新指定目录Document,如果希望文件长久保留。可以使用响应对象response中建议的文件名,

        let downloadPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first?.appending("/\(respose!.suggestedFilename!)")

        print(downloadPath)
        try! FileManager.default.moveItem(at: location!, to: URL(fileURLWithPath: downloadPath!))
    }

    task.resume()
}

大文件下载

import UIKit

class ViewController: UIViewController {

    var task:URLSessionDownloadTask?

    var session:URLSession?
    var resumeData:Data?

    //开始下载
    @IBAction func startDownload(_ sender: Any) {

        download()
    }

    //暂停下载
    @IBAction func pauseDownload(_ sender: Any) {

        task?.suspend()
    }

    //终止下载
    @IBAction func stopDownload(_ sender: Any) {

        //这种取消方式仍然可以恢复下载
        task?.cancel { (resumeData:Data?) in
            self.resumeData = resumeData
        }
    }

    //恢复下载
    @IBAction func resumeDownload(_ sender: Any) {

        // 先检测有没有已完成的数据
        if resumeData != nil {
            task = session?.downloadTask(withResumeData: resumeData!)
        }

        task?.resume()
    }

    func download() {
        let url = URL(string: "http://120.25.226.186:32812/resources/videos/minion_03.mp4")
        let request = URLRequest(url: url!)

        //使用代理监听下载进度以及完成情况
        session = URLSession.init(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
        task = session?.downloadTask(with: request)
        task?.resume()
    }
}

extension ViewController: URLSessionDownloadDelegate {

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        print(downloadTask)
        print(totalBytesWritten)
        print(totalBytesExpectedToWrite)
        print("已下载\(Int(CGFloat(totalBytesWritten) / CGFloat(totalBytesExpectedToWrite) * 100))%")
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
        //恢复下载的时候会调用

        //参数:
        //fileOffset 从什么地方下载
        //expectedTotalBytes 文件的总大小
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        let downloadPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first?.appending("/\(downloadTask.response!.suggestedFilename!)")
        try! FileManager.default.moveItem(at: location, to: URL(fileURLWithPath: downloadPath!))
        print("下载完成")
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        //请求结束
    }
}

results matching ""

    No results matching ""