URLSession委托方法不起作用

时间:2018-03-21 09:57:47

标签: ios swift api

我要从API读取文件,但它的大小等于1.6mb,需要花费很多时间。我想通过各个部分阅读它,当我找到我需要的数据时,我将停止接收数据。我尝试使用一些委托方法,但它们不起作用。我不明白出了什么问题? 我有下一个代码:

class ViewController: UIViewController, URLSessionTaskDelegate, URLSessionDelegate, URLSessionDataDelegate {

    var httpString = "hided"

    override func viewDidLoad() {
        super.viewDidLoad()
        getLogBinData()
    }

    func getLogBinData() {
        let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
        if let url = URL(string: httpString + "log.bin") {
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
            let task = session.dataTask(with: request)
            task.resume()
        }
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
        print()
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        if dataTask.countOfBytesReceived >= 500 {
            print(dataTask.countOfBytesReceived)
        }
    }

    func urlSession(_ session: URLSession,
                    dataTask: URLSessionDataTask,
                    didReceive response: URLResponse,
                    completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
        if dataTask.countOfBytesReceived >= 500 {
            print(dataTask.countOfBytesReceived)
        }
    }


}

1 个答案:

答案 0 :(得分:0)

根据评论,我编辑了代码并且它有效。

class ViewController: UIViewController, URLSessionTaskDelegate, URLSessionDelegate, URLSessionDataDelegate {

    var httpString = "hided"

    override func viewDidLoad() {
        super.viewDidLoad()
        getLogBinData()
    }

    func getLogBinData() {
        let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
        if let url = URL(string: httpString + "log.bin") {
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
            let task = session.dataTask(with: request)
            task.resume()
        }
    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        if dataTask.countOfBytesReceived >= 500 {
            print(dataTask.countOfBytesReceived)
        }
    }
}