Swift - 使用 downloadTaskWithURL 下载视频

2023-12-27

我正在通过 downloadTaskWithURL 下载视频,并使用以下代码将其保存到我的图库中:

    func saveVideoBis(fileStringURL:String){

    print("saveVideoBis");

    let url = NSURL(string: fileStringURL);
    (NSURLSession.sharedSession().downloadTaskWithURL(url!) { (location:NSURL?, r:NSURLResponse?, e:NSError?) -> Void in

        let mgr = NSFileManager.defaultManager()

        let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0];

        print(documentsPath);

        let destination = NSURL(string: NSString(format: "%@/%@", documentsPath, url!.lastPathComponent!) as String);

        print(destination);

        try? mgr.moveItemAtPath(location!.path!, toPath: destination!.path!)

        PHPhotoLibrary.requestAuthorization({ (a:PHAuthorizationStatus) -> Void in
            PHPhotoLibrary.sharedPhotoLibrary().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(destination!);
                }) { completed, error in
                    if completed {
                        print(error);
                        print("Video is saved!");
                        self.sendNotification();
                    }
            }
        })
    }).resume()
}

它在我的模拟器上工作得很好,但在我的 iPad 上,即使print("Video is saved!");出现。 你知道为什么吗?

我的控制台中也出现了该消息

无法从文件创建数据(空)


请通过代码查看注释:

Xcode 8 • 斯威夫特 3

import UIKit
import Photos

class ViewController: UIViewController {

    func downloadVideoLinkAndCreateAsset(_ videoLink: String) {

        // use guard to make sure you have a valid url
        guard let videoURL = URL(string: videoLink) else { return }

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

        // check if the file already exist at the destination folder if you don't want to download it twice
        if !FileManager.default.fileExists(atPath: documentsDirectoryURL.appendingPathComponent(videoURL.lastPathComponent).path) {

            // set up your download task
            URLSession.shared.downloadTask(with: videoURL) { (location, response, error) -> Void in

                // use guard to unwrap your optional url
                guard let location = location else { return }

                // create a deatination url with the server response suggested file name
                let destinationURL = documentsDirectoryURL.appendingPathComponent(response?.suggestedFilename ?? videoURL.lastPathComponent)

                do {

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

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

                        // check if user authorized access photos for your app
                        if authorizationStatus == .authorized {
                            PHPhotoLibrary.shared().performChanges({
                                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destinationURL)}) { completed, error in
                                    if completed {
                                        print("Video asset created")
                                    } else {
                                        print(error)
                                    }
                            }
                        }
                    })

                } catch { print(error) }

            }.resume()

        } else {
            print("File already exists at destination url")
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        downloadVideoLinkAndCreateAsset("https://www.yourdomain.com/yourmovie.mp4")
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift - 使用 downloadTaskWithURL 下载视频 的相关文章

  • NSMenu 未调用 validateMenuItem 或 menuWillOpen

    我的 Mac 应用程序有一个 NSMenu 其委托功能validateMenuItem and menuWillOpen从来没有被调用过 到目前为止 网上的解决方案都没有帮助 看来我做的一切都是对的 菜单项的选择器属于同一类 管理它的类继承
  • 转换 [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA], (id)kCVPixelBufferPixelFormatTypeKey, nil];到斯威夫特

    这里出现错误 绞尽脑汁 尝试了各种组合 找不到类型 NSDictionary 的初始化程序 该初始化程序接受类型 object Int forKey CFString 的参数列表 configure the pixel format Obj
  • 获取添加为子视图的 UIView 的可见矩形

    如上图所示 UIView A 和 UIView C 添加到 UIView B 上 B ClipToBounds 为 YES 因此红色区域不可见 是否有可能获得 A 和 C 的可见矩形 用线条显示 当我触摸视图 A 时 我需要在可见区域显示矩
  • AF网络3问题

    In AFNetworking3 表示我使用的 SSL 证书无效验证证书链 false 但现在看来该字段已被删除 我无法向我的服务器发出请求 这是请求类 import UIKit import AFNetworking class Clie
  • 在屏幕外绘制 uiview

    我想创建一个 UIView 它在调用 ViewDidLoad 时位于屏幕外 但一旦调用某个函数 我就会将其动画显示到屏幕上 用于对 UIView 进行动画处理的代码很好 但我似乎无法从屏幕外绘制 UIView 我已将故事板中的 UIView
  • Firebase获取孩子ID swift ios

    我的 Firebase 看起来像这样 贝娄Active Orders看来childs根据他们的不同有不同的名字UID 用户身份 这是我的代码 用于获取孩子的 ID 无论孩子的名字是什么 但它似乎根本不起作用 获得的正确方法是什么child
  • Xcode 8 提交时“应用程序签名中缺少 aps 环境权利”

    我有一个应用程序 我们在过去 6 个月内提交了数十个版本 并且我们确实使用 APNS 升级到 Xcode 8 后 我收到了来自 Apple 的以下电子邮件 亲爱的开发者 我们发现您最近的交货存在一个或多个问题 应用程序名称 您的交货是 成功
  • 从选项卡栏项目中删除徽章

    如何从选项卡栏项目中删除徽章我使用了下面的代码 但不适合我 UITabBarItem chatbadge appDelegate tabBarController tabBar items objectAtIndex 2 chatbadge
  • iPhone 4G 拍照时应用程序崩溃?

    我已从我的设备中拍摄照片并调整图像大小并将其设置到我的图像视图框架 但我的应用程序在拍摄照片后有时会崩溃 使用调整大小 现在我已经用 iPhone 4G 拍了这张照片 仅当许多应用程序在后台运行 多任务 时 应用程序才会崩溃 那么我该如何解
  • 继承属性,从 readonly 继承的属性中读写时不会合成 setter

    我在使用属性时发现了一个奇怪的行为 该属性被继承为只读 然后在继承的类中重新声明为读写 In A h interface A NSObject property nonatomic strong readonly NSObject some
  • 如何在 iPhone 上缩小 UIPickerView?

    我想降低一个高度UIPickerView在我的 iPhone 应用程序中 使其仅显示一行和一列 选择器视图的高度应等于行的高度 我正在使用 Interface Builder 来构建UIPickerView 但我找不到调整此控件大小的简单方
  • 在从初始化器返回 nil 之前,必须初始化类实例的所有存储属性

    尽管我不断收到上述消息 但我正在尝试在课堂上使用此代码 let filePath NSString let fileHandle NSFileHandle let totalFileLength CUnsignedLongLong init
  • 检查文件是否是别名 Swift

    如何在 Mac 上检查文件是否为别名 到目前为止 这是我的代码 public func getFiles let folderPath Users timeBro Desktop testfolder let fileManager NSF
  • AVAudioSessionPortBluetoothHFP、A2DP 和 LE 有什么区别?

    Apple 中记录了三种不同的蓝牙相关音频端口类型AVAudioSessionPort 描述 https developer apple com library ios documentation AVFoundation Referenc
  • 如何通过GPUImage调整图像的亮度和对比度?

    我编写了一种使用亮度因子和对比度因子过滤图像的方法 如下所示 UIImage image UIImage image withBrightness float brightness contrast float contrast GPUIm
  • 使用Apple80211 api时如何知道OPEN、WPA、WPA2、WEP等安全类型?

    Cydia中的Wifi WiFi FoRum等wifi扫描应用可以知道安全类型 使用 Apple80211 api 时 应用程序如何知道 OPEN WPA WPA2 WEP 等安全类型 CAPABILITIES 的值为 1057 1025
  • 查询链接到 GeoFire 的 firebase 数据

    读完这些问题后 将 Geofire 位置与 Firebase 条目关联 https stackoverflow com questions 33885733 associate geofire location with firebase
  • 在 iPhone 应用程序中获取路线和路线导航

    我正在开发一款应用程序 该应用程序将重点关注在驾驶时为用户提供路线和逐段指示 他们在驾驶过程中留在应用程序中非常重要 因此我真的不想让他们离开应用程序并转到内置的地图应用程序 我最近对如何包含此功能进行了大量研究 众所周知 这并不容易 因为
  • UICollectionViewFlowLayout IOS的​​minimumLineSpacing属性

    对于UICollectionViewFlowLayout的属性minimumLineSpacing 苹果的文档说 对于垂直滚动网格 该值表示最小值 连续行之间的间距 对于水平滚动的网格 该值表示连续列之间的最小间距 我测试它和代码的一部分是
  • 如何使用 Swift 将文本复制到剪贴板/粘贴板

    我正在寻找一个干净的示例 说明如何将文本复制到 iOS 剪贴板 然后可以在其他应用程序中使用 粘贴 该功能的好处是可以快速复制文本 无需传统文本复制的标准文本突出显示功能 我假设关键课程位于UIPasteboard 但在中找不到相关区域他们

随机推荐