继续在我的ios应用程序的后台/其他屏幕上下载

时间:2022-06-15 01:23:58

I have a download function working perfectly, on click of my button, the file is being download correctly.

我有一个完美的下载功能,点击我的按钮,文件正在正确下载。

What I am trying to achieve, If I put the App in the background or change screen while it's downloading the file, I'd like the download to be continued. Currently if the App is in the background ,the download stop and user need to restart it from zero.

我想要实现的目标,如果我将应用程序置于后台或在下载文件时更改屏幕,我希望继续下载。目前,如果应用程序处于后台,则下载停止和用户需要从零重新启动它。

How is this possible to make ?? Below is my download function, I tried to add a background download without success.

这怎么可能?下面是我的下载功能,我试图添加后台下载但没有成功。

 func createDownloadTask() {
        let downloadRequest = URLRequest(url: URL(string: "\(posts[selectedIndexPath].link)")!)
        let session = Foundation.URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)

        downloadTask = session.downloadTask(with: downloadRequest)
        downloadTask!.resume()


    }

and

@IBAction func startDownload(_ sender: UIButton) {


    let urlString = "\(posts[selectedIndexPath].link)"

    DispatchQueue.global(qos: .default).async(execute: {
                 print("downloadVideo");
        let url=NSURL(string: urlString);
        let urlData=NSData(contentsOf: url! as URL);

        if((urlData) != nil)
        {
            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

            let fileName = urlString as NSString;

            let filePath="\(documentsPath)/\(fileName.lastPathComponent)";

            DispatchQueue.main.async(execute: { () -> Void in

                print(filePath)
                urlData?.write(toFile: filePath, atomically: true);
                print("video Saved to document directory of app");
                self.downloadButton.alpha = 0;
                self.progressView.alpha = 0;
                self.cardboardButton.alpha = 1;
                self.videoButton.alpha = 1;
                self.removefile.alpha = 1;

            })
        }
    })



}

1 个解决方案

#1


1  

You need to use UIBackgroundTaskIdentifier. You can start some task in background with beginBackgroundTask see: https://developer.apple.com/reference/uikit/uiapplication/1623031-beginbackgroundtask. System will give you some time and you can finish your task. If the time expire you will receive handler.See example that I use to upload a image

您需要使用UIBackgroundTaskIdentifier。您可以使用beginBackgroundTask在后台启动一些任务,请参阅:https://developer.apple.com/reference/uikit/uiapplication/1623031-beginbackgroundtask。系统会给你一些时间,你可以完成你的任务。如果时间到期,您将收到处理程序。请参阅我用于上传图像的示例

  static var backgroundUpload:UIBackgroundTaskIdentifier?
static func praiseCollegue(praiseCollegueId:Int,image:UIImageView,praisedBy:Int,praiseText:String,praiseCategory:Int,successBlock: (()->())?,errorBlock: (()->())?){
    backgroundUpload = UIApplication.shared.beginBackgroundTask(expirationHandler: {
        if let task = self.backgroundUpload{
            UIApplication.shared.endBackgroundTask(task)
        }

    })

    let url = NSURL(string: "someUrl")

    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "POST"
    request.setValue(InfoManager.sharedInstance.tokenInfo?.accessToken, forHTTPHeaderField: "AccessToken")


    let session = URLSession.shared
    let task = session.dataTask(with: request as URLRequest) {
        (
        data, response, error) in
        if let responseData = data{
            do {
                if let dict = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject]{
                    if let errorCode = dict["errorCode"] as? Int{
                        if(errorCode == 1){
                            successBlock?()
                            if let task = self.backgroundUpload{
                                UIApplication.shared.endBackgroundTask(task)
                            }
                        }
                        else{
                            errorBlock?()
                            if let task = self.backgroundUpload{
                                UIApplication.shared.endBackgroundTask(task)
                            }
                        }
                    }
                }
            }
        }
    }

    task.resume()

}

#1


1  

You need to use UIBackgroundTaskIdentifier. You can start some task in background with beginBackgroundTask see: https://developer.apple.com/reference/uikit/uiapplication/1623031-beginbackgroundtask. System will give you some time and you can finish your task. If the time expire you will receive handler.See example that I use to upload a image

您需要使用UIBackgroundTaskIdentifier。您可以使用beginBackgroundTask在后台启动一些任务,请参阅:https://developer.apple.com/reference/uikit/uiapplication/1623031-beginbackgroundtask。系统会给你一些时间,你可以完成你的任务。如果时间到期,您将收到处理程序。请参阅我用于上传图像的示例

  static var backgroundUpload:UIBackgroundTaskIdentifier?
static func praiseCollegue(praiseCollegueId:Int,image:UIImageView,praisedBy:Int,praiseText:String,praiseCategory:Int,successBlock: (()->())?,errorBlock: (()->())?){
    backgroundUpload = UIApplication.shared.beginBackgroundTask(expirationHandler: {
        if let task = self.backgroundUpload{
            UIApplication.shared.endBackgroundTask(task)
        }

    })

    let url = NSURL(string: "someUrl")

    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "POST"
    request.setValue(InfoManager.sharedInstance.tokenInfo?.accessToken, forHTTPHeaderField: "AccessToken")


    let session = URLSession.shared
    let task = session.dataTask(with: request as URLRequest) {
        (
        data, response, error) in
        if let responseData = data{
            do {
                if let dict = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject]{
                    if let errorCode = dict["errorCode"] as? Int{
                        if(errorCode == 1){
                            successBlock?()
                            if let task = self.backgroundUpload{
                                UIApplication.shared.endBackgroundTask(task)
                            }
                        }
                        else{
                            errorBlock?()
                            if let task = self.backgroundUpload{
                                UIApplication.shared.endBackgroundTask(task)
                            }
                        }
                    }
                }
            }
        }
    }

    task.resume()

}