Search code examples
iosswiftavasset

getting error when i trying to convert AVAssetURL to Data


Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_9807.MOV” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/var/mobile/Media/DCIM/109APPLE/IMG_9807.MOV, NSUnderlyingError=0x1c1e5fe00 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"

i am sending asset URL to other controller and try to convert into data

PHImageManager.default().requestAVAsset(forVideo: self.albumView.phAsset, options: options) { (video, audioMix, info) in
                DispatchQueue.main.async {
                     let urlAsset = video as! AVURLAsset
                    self.dismiss(animated: false, completion: {
                        self.delegate?.fusumaVideoCompleted(withFileURL: urlAsset.url)
                    })
                }
            }

here below methods for convert AVAssetUrl to data

 do {
                let data = try Data(contentsOf: product.videoURL, options: .mappedIfSafe)
                return .upload(.multipart([MultipartFormData(provider: .data(data), name: "post[video]", fileName: "video.\(pathExtension)", mimeType: "video/\(pathExtension)")]))
            } catch {
                debugPrint(error)
            }

Solution

  • As the error tells you, you cannot access the video file in the user's photo library by way of its URL for purposes of uploading it. You should obtain the video data and upload that. A video is very big, so you should not get the data directly and hold it in memory; instead, export the data to a file in a place that you are allowed to access, such as the Temporary folder.

    To do that, you might (for example) use this method:

    https://developer.apple.com/documentation/photos/phassetresourcemanager/1616280-writedata

    Or this one:

    https://developer.apple.com/documentation/photos/phimagemanager/1616981-requestexportsession

    If you use the Mail app to email a video from your own device's photo library, you will actually see that happening; there is a pause with a progress bar while the video is exported, and then the email is constructed.