documentsフォルダの中にtest1フォルダを生成してそこに画像を保存したいと思っています。おそらくtest1フォルダは生成できているはずなのですが、写真を保存しようとするとエラーが発生してしまいます。
色々調べてみたのですが治らなかったため質問させていただきました。swift初心者なので丁寧に教えていただけるとありがたいです。Xcodeのバージョンは11.3.1です。
info.plistには
Privacy - Camera Usage Description
Privacy - Photo Library Usage Description
Application supports iTunes file sharing YES
Supports opening documents in place YES
を追加しています。
swift
1import UIKit 2import DKImagePickerController 3import Photos 4 5class viewPhotoController1: UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate{ 6 7 override func viewDidLoad() { 8 super.viewDidLoad() 9 10 // Do any additional setup after loading the view 11 //directory 作成 12 let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) 13 let documetnsDirectory = paths[0] 14 let docURL = URL(string: documetnsDirectory)! 15 let datapath = docURL.appendingPathComponent("test1") 16 if !FileManager.default.fileExists(atPath: datapath.absoluteString) { 17 do { 18 try FileManager.default.createDirectory(atPath: datapath.absoluteString, withIntermediateDirectories: true, attributes: nil) 19 } catch { 20 print("フォルダの作成に失敗!,error=(error)"); 21 } 22 } 23 } 24 25 26 /* 27 // MARK: - Navigation 28 29 // In a storyboard-based application, you will often want to do a little preparation before navigation 30 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 31 // Get the new view controller using segue.destination. 32 // Pass the selected object to the new view controller. 33 } 34 */ 35 //画像保存 36 //画像を保存するメソッド jpegに直して保存 37 func saveImage (image: UIImage?, path: String ) -> Bool { 38 let jpgImageData = image?.jpegData(compressionQuality:0.5) 39 do { 40 try jpgImageData!.write(to: URL(fileURLWithPath: path), options: .atomic) 41 } catch { 42 print(error) 43 return false 44 } 45 return true 46 } 47 48 49 50 @IBAction func addPhoto1(_ sender: Any) { 51 //カメラかフォトライブラリどちらから画像を取得するか選択 52 let alertController = UIAlertController(title: "確認", message: "選択してください", preferredStyle: .actionSheet) 53 //まず、使用可能かを確認してからカメラ、フォトライブラリを起動するための選択肢を定義 54 if UIImagePickerController.isSourceTypeAvailable(.camera){ 55 let cameraAction = UIAlertAction(title: "カメラ", style: .default, handler: { 56 (action: UIAlertAction) in 57 //カメラを起動 58 let imagePickerController = UIImagePickerController() 59 imagePickerController.sourceType = .camera 60 imagePickerController.delegate = self 61 self.present(imagePickerController, animated: true, completion: nil) 62 63 }) 64 alertController.addAction(cameraAction) 65 } 66 if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){ 67 let photoLibraryAction = UIAlertAction(title: "フォトライブラリー", style: .default, handler:{ 68 (action: UIAlertAction) in 69 //フォトライブラリを起動 70 let dkImagePickerController = DKImagePickerController() 71 //無制限に選択可能 72 dkImagePickerController.maxSelectableCount = 0 73 dkImagePickerController.sourceType = .photo 74 dkImagePickerController.showsCancelButton = true 75 dkImagePickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in 76 //選択された画像はassetsに入れて返却されるのでfetch して取り出す。 77 for asset in assets { 78 asset.fetchFullScreenImage(completeBlock: {(image,info) in 79 let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) 80 let documetnsDirectory = paths[0] 81 let docURL = URL(string: documetnsDirectory)! 82 let datapath = docURL.appendingPathComponent("test1") 83 let datapathString = datapath.absoluteString 84 //ここで取り出せる,このimageはUIImage?型 85 self.saveImage(image: image, path: datapathString) 86 }) 87 } 88 } 89 self.present(dkImagePickerController, animated: true, completion: nil) 90 }) 91 alertController.addAction(photoLibraryAction) 92 } 93 //キャンセルの選択肢を定義 94 let cancelAction = UIAlertAction(title: "キャンセル", style: .cancel, handler: nil) 95 alertController.addAction(cancelAction) 96 //ipadで落ちてしまう対策 97 alertController.popoverPresentationController?.sourceView = view 98 //選択肢を画面に表示 99 present(alertController, animated: true, completion: nil) 100 101 } 102 103 //撮影が終わった時に呼ばれるdelegateメソッド 104 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { 105 let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) 106 let documetnsDirectory = paths[0] 107 let docURL = URL(string: documetnsDirectory)! 108 let datapath = docURL.appendingPathComponent("test1") 109 let datapathString = datapath.absoluteString 110 111 let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage 112 //撮影した画像をdocumentsに保存する 113 if saveImage(image: image, path: datapathString){ 114 //モーダルビューを閉じる 115 dismiss(animated: true, completion: nil) 116 } 117 else { 118 //確認したのち結局モーダルビューを閉じる 119 let alertController = UIAlertController(title: "エラー", message: "画像を保存できませんでした", preferredStyle: .actionSheet) 120 let confirmAction = UIAlertAction(title: "確認", style: .cancel, handler: nil) 121 alertController.addAction(confirmAction) 122 dismiss(animated: true, completion: nil) 123 } 124 } 125 126}
error
12020-03-29 13:02:14.534088+0900 scheduleApplication[71992:3976250] [core] "Error returned from daemon: Error Domain=com.apple.accounts Code=7 "(null)"" 2Error Domain=NSCocoaErrorDomain Code=512 "The file “test1” couldn’t be saved in the folder “Documents”." 3UserInfo={NSFilePath=/Users/xxx/Library/Developer/CoreSimulator/Devices/E3F54F80-F31A-4179-BD90-F994531B9552/data/Containers/Data/Application/D0F8AA88-F18F-44DD-8308-82308E4E5008/Documents/test1, NSUnderlyingError=0x600003c18720 {Error Domain=NSPOSIXErrorDomain Code=21 "Is a directory"}}
回答1件
あなたの回答
tips
プレビュー