草庐IT

ios swift 从 url 下载视频到手机图库

coder 2023-09-15 原文

我正在使用 URLSessionDownloadTask 从 url 下载视频到我的手机图库,我如何设置下载的视频文件的目标路径,我需要它出现在我的手机视频文件夹中。

var downloadTask: URLSessionDownloadTask!
var backgroundSession: URLSession!

if let theUrl = url {

  downloadTask = backgroundSession.downloadTask(with: theUrl)
  downloadTask.resume()
}

extension DownloadVideoViewController : URLSessionDownloadDelegate {


    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {

        if self.downloadTask != nil {
            self.displyAlertWithAction(title: "Complete", message: "Download finished")
        }
    }


    func urlSession(_ session: URLSession,downloadTask: URLSessionDownloadTask,didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
    {
        print("\nDownload started ....Total is \(Float(totalBytesExpectedToWrite)/(1024*1024)) Mb")
        print("\nWritten \(totalBytesWritten) bytes")
        progressView.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true)
    }

    func urlSession(_ session: URLSession,task: URLSessionTask,didCompleteWithError error: Error?)
    {
        if (error != nil) {
            print(error!.localizedDescription)
        }else{
            if downloadTask != nil {
                print("The task finished transferring data successfully")
                downloadTask = nil
                progressView.setProgress(0.0, animated: true)
            }

        }
    }

}

最佳答案

您可以像下面的代码示例一样设置目标路径。

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {

   let url = downloadTask.response?.url?.lastPathComponent

   if (url?.hasSuffix(".mp4"))! // for check video download
   {

    SVProgressHUD.dismiss() // dismiss the HUD
    guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

    if !FileManager.default.fileExists(atPath: documentsDirectoryURL.appendingPathComponent((downloadTask.response?.url?.lastPathComponent)!).path) {    // the video already exist in path

        // create a deatination url with the server response suggested file name

        let destinationURL = documentsDirectoryURL.appendingPathComponent(downloadTask.response?.suggestedFilename ?? ((downloadTask.response?.url)?.lastPathComponent)!)

        do {

            try FileManager.default.moveItem(at: location, to: destinationURL)


            PHPhotoLibrary.requestAuthorization({(authorizationStatus: PHAuthorizationStatus) -> Void in

                var identifier = ""

                // check if user authorized access photos for your app
                if authorizationStatus == .authorized {
                    PHPhotoLibrary.shared().performChanges({

                        let createassetrequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destinationURL)
                        let assetplaceholder = createassetrequest?.placeholderForCreatedAsset

                        let albumchange = PHAssetCollectionChangeRequest(for: self.assetcol.assetCollection)
                        albumchange?.addAssets([assetplaceholder as Any] as NSArray)

                        identifier = (assetplaceholder?.localIdentifier)!
                        print(identifier)

                    })
                    {  completed, error in
                        if completed {

                            DispatchQueue.main.async {

                                print("Video saved") // successfully saved video in your gallery
                            }

                        } else {
                            print(error as Any)
                        }
                    }
                }
            })

        } catch { print(error) }

    }
    else // video not already exist in this destination path.
    {

        SVProgressHUD.dismiss()

        let destinationURL = documentsDirectoryURL.appendingPathComponent(downloadTask.response?.suggestedFilename ?? ((downloadTask.response?.url)?.lastPathComponent)!)

        do {

            try FileManager.default.removeItem(at: destinationURL)
            try FileManager.default.moveItem(at: location , to: destinationURL)

            PHPhotoLibrary.requestAuthorization({ (authorizationStatus: PHAuthorizationStatus) -> Void in

                var identifier = ""
                // check if user authorized access photos for your app
                if authorizationStatus == .authorized {
                    PHPhotoLibrary.shared().performChanges({

                        let createassetrequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destinationURL)
                        let assetplaceholder = createassetrequest?.placeholderForCreatedAsset

                        let albumchange = PHAssetCollectionChangeRequest(for: self.assetcol.assetCollection)
                        albumchange?.addAssets([assetplaceholder as Any] as NSArray)

                        identifier = (assetplaceholder?.localIdentifier)!
                        print(identifier)

                      }) { completed, error in
                        if completed {

                            DispatchQueue.main.async {

                                print("Video saved") // saved video successfully.

                            }

                        } else {
                            print(error as Any)
                        }
                    }
                }
            })

        } catch { print(error) }

    }
}
else // something like image if not video
{

}

  }


func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {

    DispatchQueue.main.async {

        let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
        SVProgressHUD.showProgress(progress, status: "Downloading")

    }
}
}

希望对你有帮助

关于ios swift 从 url 下载视频到手机图库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52359144/

有关ios swift 从 url 下载视频到手机图库的更多相关文章

  1. ruby-on-rails - rails : save file from URL and save it to Amazon S3 - 2

    从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex

  2. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

  3. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  4. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  5. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  6. ruby - Rack:如何将 URL 存储为变量? - 2

    我正在编写一个简单的静态Rack应用程序。查看下面的config.ru代码:useRack::Static,:urls=>["/elements","/img","/pages","/users","/css","/js"],:root=>"archive"map'/'dorunProc.new{|env|[200,{'Content-Type'=>'text/html','Cache-Control'=>'public,max-age=6400'},File.open('archive/splash.html',File::RDONLY)]}endmap'/pages/search.

  7. Unity 热更新技术 | (三) Lua语言基本介绍及下载安装 - 2

    ?博客主页:https://xiaoy.blog.csdn.net?本文由呆呆敲代码的小Y原创,首发于CSDN??学习专栏推荐:Unity系统学习专栏?游戏制作专栏推荐:游戏制作?Unity实战100例专栏推荐:Unity实战100例教程?欢迎点赞?收藏⭐留言?如有错误敬请指正!?未来很长,值得我们全力奔赴更美好的生活✨------------------❤️分割线❤️-------------------------

  8. ruby-on-rails - Rails - 使用/自定义 URL : '/dashboard' 指定根路径 - 2

    如何使此根路径转到:“/dashboard”而不仅仅是http://example.com?root:to=>'dashboard#index',:constraints=>lambda{|req|!req.session[:user_id].blank?} 最佳答案 您可以通过以下方式实现:root:to=>redirect('/dashboard')match'/dashboard',:to=>"dashboard#index",:constraints=>lambda{|req|!req.session[:user_id].b

  9. 动漫制作技巧如何制作动漫视频 - 2

    动漫制作技巧是很多新人想了解的问题,今天小编就来解答与大家分享一下动漫制作流程,为了帮助有兴趣的同学理解,大多数人会选择动漫培训机构,那么今天小编就带大家来看看动漫制作要掌握哪些技巧?一、动漫作品首先完成草图设计和原型制作。设计草图要有目的、有对象、有步骤、要形象、要简单、符合实际。设计图要一致性,以保证制作的顺利进行。二、原型制作是根据设计图纸和制作材料,可以是手绘也可以是3d软件创建。在此步骤中,要注意的问题是色彩和平面布局。三、动漫制作制作完成后,加工成型。完成不同的表现形式后,就要对设计稿进行加工处理,使加工的难易度降低,并得到一些基本准确的概念,以便于后续的大样、准确的尺寸制定。四、

  10. python ffmpeg 使用 pyav 转换 一组图像 到 视频 - 2

    2022/8/4更新支持加入水印水印必须包含透明图像,并且水印图像大小要等于原图像的大小pythonconvert_image_to_video.py-f30-mwatermark.pngim_dirout.mkv2022/6/21更新让命令行参数更加易用新的命令行使用方法pythonconvert_image_to_video.py-f30im_dirout.mkvFFMPEG命令行转换一组JPG图像到视频时,是将这组图像视为MJPG流。我需要转换一组PNG图像到视频,FFMPEG就不认了。pyav内置了ffmpeg库,不需要系统带有ffmpeg工具因此我使用ffmpeg的python包装p

随机推荐