
前提
mp4ファイルをアルバムに保存しようとすると失敗します
実現したいこと
https://hogehoge.com/movie/21838381818.mp4 から動画をダウンロードしてiPhoneのアルバムに保存したいです
アルバムへの保存の流れも知りたいです
発生している問題・エラーメッセージ
Optional(Error Domain=PHPhotosErrorDomain Code=3302 "(null)") Optional("The operation couldn’t be completed. (PHPhotosErrorDomain error 3302.)")
該当のソースコード
swift
1 import Photos 2 3class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate { 4 5// 保存 6 @IBAction func saveMovie(_ sender: Any) { 7 8 let url = URL(string: self.url!) 9 10 let request = URLRequest(url: url!) 11 12 let task = URLSession.shared.dataTask(with: request) { (data, response, error) in 13 14 if(data == nil){ 15 print("ダウンロード失敗") 16 return 17 } 18 19 if data!.count == 0 { 20 print("中身がない") 21 22 } else { 23 print("ダウンロード開始") 24 25 //ドキュメントフォルダのパス 26 let path = NSSearchPathForDirectoriesInDomains( 27 .documentDirectory, 28 .userDomainMask, true).last! 29 30 //ファイルのパス 31 let documentDirectoryURL = path 32 33 do { 34 //アプリ内に保存 35 try data?.write(to: URL(fileURLWithPath: documentDirectoryURL)) 36 print("documentDirectoryURLは") 37 print(documentDirectoryURL) 38 39 PHPhotoLibrary.shared().performChanges( 40 { 41 PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(string: documentDirectoryURL)!) 42 }, 43 completionHandler: { (success, err) in 44 if success == true { 45 print("保存成功!") 46 } else { 47 print("保存失敗! \(err) \(err?.localizedDescription)") 48 } 49 }) 50 } catch { 51 print(error.localizedDescription) 52 } 53 } 54 } 55 task.resume() 56 } 57} 58
// 出力結果 ダウンロード開始 documentDirectoryURLは /Users/apple/Library/Developer/CoreSimulator/Devices/AE..../data/Containers/Data/Application/98.../Documents
試したこと①
試したこと②
do { try ...} catch {error.localizedDescription} 追記
// 出力結果② The file “Documents” couldn’t be saved in the folder "22-....-.....”.
補足情報(FW/ツールのバージョンなど)
Xcode 13.4

https://stackoverflow.com/questions/61044285/save-video-in-photo-library-swift
リンク先などを見ると流れはOKっぽいのでしょうかね。
気になったのは次のコードです。
`try? data?.write(to: URL(fileURLWithPath: documentDirectoryURL))`
tryの部分でエラーをオプショナルな値に変換するのではなく、
エラーの場合はどのようなエラーが発生しているのか把握するために
do-catchステートメントで処理してみたらいかがでしょうか。

コメントありがとうございます。
do { try...} catch { print(error.localizedDescription)} でやると
`The file “Documents” couldn’t be saved in the folder “22...-....”.`
と出るのでファイル名の重複が原因かもしれません

回答1件
あなたの回答
tips
プレビュー