swift – Is there any way to write/copy/move files from iOS application to OTG usb connected to iOS device?


I want to copy file that downloaded from server and stored in document directory to OTG usb device connected to my iPhone, I can get path of usb device but when I want to copy, move or write file to usb I get errors The file “STORAGE” couldn’t be saved in the folder “com.apple.filesystems.userfsd” and Permission denied (“Storage” is name of the usb device).

I used UIDocumentPickerViewController to get path of the usb.

I’ve tried to write data:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let selectedURL = urls.first else { return }
        do {
            let shouldStopAccessing = selectedURL.startAccessingSecurityScopedResource()
            defer {
                if shouldStopAccessing {
                    selectedURL.stopAccessingSecurityScopedResource()
                }
            }
            let data = try Data(contentsOf: fileURL!).base64EncodedData()
            try data.write(to: selectedURL, options: .noFileProtection)
            print("Data written successfully!")
            do {
                try FileManager.default.removeItem(atPath: fileURL!.path)
            } catch {
                print("Could not delete file, probably read-only filesystem")
            }
        } catch {
            print("Error writing data: \(error.localizedDescription)")
        }
    }

even copy file with FileManager:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let selectedURL = urls.first else { return }
        do {
            let shouldStopAccessing = selectedURL.startAccessingSecurityScopedResource()
            defer {
                if shouldStopAccessing {
                    selectedURL.stopAccessingSecurityScopedResource()
                }
            }
            try FileManager.default.copyItem(at: fileURL!, to: selectedURL)
            print("Data written successfully!")
            do {
                try FileManager.default.removeItem(atPath: fileURL!.path)
            } catch {
                print("Could not delete file, probably read-only filesystem")
            }
        } catch {
            print("Error writing data: \(error.localizedDescription)")
        }
    }

But none of these methods worked.

Is there any way to copy the file to the USB from iOS application?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img