SoFunction
Updated on 2025-04-12

iOS uses NSURLConnection to achieve breakpoint continuous transmission download

This example shares the specific code for iOS using NSURLConnection to achieve breakpoint continuous transmission and download for your reference. The specific content is as follows

1. The principle of breakpoint continuous transmission

The principle of breakpoint continuous transmission: Every time the server requests to download data, you must tell the server to start downloading from a location that has not been downloaded in the entire download file data stream, and then the server returns the data stream from which location it started.

2. Implementation of breakpoint continuous transmission

first step:Declare some attributes first

fileprivate var totalSize: Int64 = 0   // Total sizefileprivate var currentSize: Int64 = 0 // Current sizefileprivate var fileName: String?      // file namefileprivate var fullPath: String?      // File Lu Jinfileprivate var handle: FileHandle?    // Handlefileprivate var connection: NSURLConnection?

Step 2:Create URLs and requests

The key is to set the request header

// Download the filefunc urlConnectionDownload(_ url: String) -> NSURLConnection? {
        var request = URLRequest(url: URL(string: url)!)
        // Set request header information        /*
 bytes=0-1000 indicates that data of 0-1000 is downloaded
 bytes=0-   Indicates that download starts from 0 until the download is completed
 bytes=100-   Indicates that download starts from 100 until the download is completed
 */
        ("bytes=\(currentSize)", forHTTPHeaderField: "Range")
        // Send asynchronous request        connection = NSURLConnection(request: request, delegate: self)
        return connection
    }
    // Cancel download the file    func urlConnectionCacel() {
        connection?.cancel()
    }

Step 3:Set up proxy NSURLConnectionDataDelegate

Step 4:Implement the proxy NSURLConnectionDataDelegate method

// When receiving the response header information, it will be called (the first method called), and it will only be called once    func connection(_ connection: NSURLConnection, didReceive response: URLResponse) {
        print("didReceive response")
        // Determine whether it has been downloaded        if currentSize > 0 {
            // If you have already downloaded it, you don't need to accept the response again            return
        }
        // Total file size        totalSize = 
        // The file name obtained        fileName = 
        //Write files into the sandbox while receiving data        // 1. Get the full path of the file        if let cache = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last {
            let nsCache = cache as NSString
            fullPath = (fileName!)
            // Create an empty file            (atPath: fullPath!, contents: nil, attributes: nil)
            // Create a handle            handle = FileHandle(forWritingAtPath: fullPath!)
        }
    }
    
    func connection(_ connection: NSURLConnection, didReceive data: Data) {
        print("didReceive data")
        // Move the file handle to the end of the file        handle?.seekToEndOfFile()
        // Write data using file handle        handle?.write(data)
        currentSize += 
        print(currentSize / totalSize)
    }
    
    func connectionDidFinishLoading(_ connection: NSURLConnection) {
        print("didFinish loading")
        print(fullPath!)
        handle?.closeFile()
        handle = nil
    }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.