Download videos and save them to your mobile album

Function description: The transcoded video (less than 20MB) needs to be downloaded to the mobile phone album through APP to share the small video to WeChat.

1. Video is transcoded from the server, or many cloud providers will provide this functionality.

2. Download to mobile photo album via APP, this is what we need to do.

Main Techniques: Use URLSession and URLSessionDownload Delegate

1. Create a session download task and execute it (since the downloaded video is smaller, all do not need to be downloaded in segments)

        //  Initialize session
        let config = URLSessionConfiguration.default;
        let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue());
        //  Video Address
        let url = URL(string: urlStr.addingPercentEncoding(withAllowedCharacters:.urlQueryAllowed)!);
        //  Create Request
        let request = URLRequest(url: url!);
        let download = session.downloadTask(with: request);
        //  Start task, session task is suspended by default, need resume to execute
        download.resume();

2. Set the URLSessionDownloadDelegate proxy method

    //Called when the download is complete, location is the path after the download is complete
    @available(iOS 7.0, *)
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)

    //Download progress, called multiple times during download
    //bytesWritten: Bytes written this time, totalBytesWritten: Bytes written (bytes currently downloaded), totalBytesExpectedToWrite: Bytes downloaded (total file size)
    @available(iOS 7.0, *)
    optional public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)

    //Continue downloading,
    @available(iOS 7.0, *)
    optional public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64)
Upper Code

//  Complete Call
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        //  1. The output location is in file:///user... format, which needs to be truncated and converted to String format.
        //  2. The downloaded files are saved in the sandbox tmp folder (temporary files) by default. After this method, the system will delete them automatically, so you need to save and modify the file format
        //  Convert source file URL address to String
        let locationStepOne = location.absoluteString as NSString;
        //  Truncate file://
        let locationStepTwo = locationStepOne.substring(from: 7);
        
        //  Create File Manager
        let manager = FileManager.default;
        //  Under the destination address cache folder
        let pathArray = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true);
        //  Generate Destination Address
        let copyPath = pathArray.first! + "/video.mov";
        //  Determine whether a file exists, delete it if it exists
        let exist = manager.fileExists(atPath: copyPath);
        if exist {
            //  Yes, delete
            let cancel:Bool = ((try?manager.removeItem(atPath: copyPath)) != nil);
            if !cancel {
                return;
            }
        }
        //  Copy file TMP -> cache
        let save:Bool = ((try? manager.moveItem(atPath: locationStepTwo, toPath: copyPath)) != nil);
        if save {
            //  Detect if files can be saved to an album
            if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(copyPath) {
                //  Save in Album
                UISaveVideoAtPathToSavedPhotosAlbum(copyPath, self, nil, nil);
            }
        } else {
            print("fail");
        }
    }
    //  Download Progress
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        //  Get Progress
        let written:Float = (Float)(totalBytesWritten);
        let total:Float = (Float)(totalBytesExpectedToWrite);
        let progress:Float = written/total;
    }
    //  Continue downloading
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
        
    }

Tags: Session iOS Mobile less

Posted on Sat, 23 May 2020 12:38:06 -0400 by sheilam