Search code examples
iosswiftupload

Measure upload speed in swift


I have my own server in which I want to upload my file to in Swift. I also want to measure the upload speed. Below I create an empty 1 mb Data object and upload it.

        let urlString = "https://myserver/upload.php"
        guard let url = URL(string: urlString) else {
            return
        }

        var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10)
        urlRequest.httpMethod = "POST"
        urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")

        let emptyData = createEmptyData(of: 1048576)

        let json = ["file" : emptyData]
        urlRequest.httpBody = try? JSONEncoder().encode(json)

        let sessionConfiguration = URLSessionConfiguration.ephemeral
        let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)

        session.dataTask(with: urlRequest).resume()

How do I measure the upload speed? Thanks


Solution

  •       let urlString = "https://myserver/upload.php"
          guard let url = URL(string: urlString) else {
             return
          }
    
         var timer: Timer?
         var uploadTask: URLSessionUploadTask!
    
         var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10)
         urlRequest.httpMethod = "POST"
         urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
    
         let emptyData = Data.init(capacity: 102454)
    
         let json = ["file" : emptyData]
         urlRequest.httpBody = try? JSONEncoder().encode(json)
    
         let sessionConfiguration = URLSessionConfiguration.ephemeral
         let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
         uploadTask = session.uploadTask(with: urlRequest, from: emptyData) { (data, response, error) in
            if let err = error {
                //There's an error
            }
            else if let response = response {
                //check for response status
            }
    
            //Stop the timer here
            timer?.invalidate()
          }
    
        uploadTask.resume()
        calculateSpeed()
    }
    
    
    func calculateSpeed() {
        var previousBytesSent: Int64 = 0
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (_) in
            let bytesSent = uploadTask.countOfBytesSent
            let speed =  abs(bytesSent-previousBytesSent)
            //Here you get the speed in Bytes/sec
            previousBytesSent = bytesSent
        })
    }