Swift 自アプリフォルダ確認、ファイル存在確認・削除・コピーのExample

2021年9月1日

UIDocumentPickerViewControllerView使用、ファイル選択後の処理

Exmaple

extension UIDocumentPickerViewControllerView: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard urls.count != 0 else {
            return
        }
        print(#function)
        print(urls.debugDescription)
        print(urls[0].lastPathComponent)

        let fileManager = FileManager.default
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        
        print(documentsPath)

        let filePath = documentsPath + "/" + urls[0].lastPathComponent
            
        if urls[0].absoluteString.contains(documentsPath) == true {
            print("My App Folder")
            let _ = urls[0].startAccessingSecurityScopedResource()
            // 何か処理!!
            let _ = urls[0].stopAccessingSecurityScopedResource()
        }
        else {
            do {
                if fileManager.fileExists(atPath: filePath) == true {
                    print("same name exists")
                    try fileManager.removeItem(atPath: filePath)
                    print("remove file:\(filePath)")
                }
                if fileManager.fileExists(atPath: urls[0].absoluteString) == false {
                    let _ = urls[0].startAccessingSecurityScopedResource()
                    try fileManager.copyItem(at: urls[0], to: URL(fileURLWithPath: filePath))
                    // 何か処理!!
                    print(filePath)
                    let _ = urls[0].stopAccessingSecurityScopedResource()
                }
            }
            catch let error {
                print(error)
            }
        }
    }
}

SwiftSwift

Posted by shi-n