Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a file in swift

Tags:

xcode

swift

I'm trying to move a file to documents directory after I choose the file by using UIDocumentPickerViewController.

I don't see any error, but the file doesn't move to the directory.

I'd like to know how can I move the file.

class MyClassController: UIViewController,UIDocumentPickerDelegate {

 var thisURL:URL?   

  @IBAction func add(_ sender: Any) {


    let add = UIAlertAction(title: "add", style: .default, handler: {(alert: UIAlertAction!) in                         
          do {

            let myURL = URL(string:"\(self.thisURL!)")!


                   let path = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)


                let MyDesPath = path.appendingPathComponent(myURL.lastPathComponent)

                            print(path)
                                do {
                                if FileManager.default.fileExists(atPath: “\(MyDesPath)") == false {
                                                                           try  FileManager.default.moveItem(at: myURL, to: URL(string:”\(MyDesPath)")!)

                                                                       }
                                                                       else {

                                                                       }
                                                                      }
                                                                        catch let error {
                                                                         print(error)
                                                                     }

                                                                           }

                                                                     catch let error{
                                                                         print(error)
                                                                         return
                                                                     }

    })
 func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
     NSLog("documentPicker executed")
    thisURL = urls[0]

    self.fileName.text = "\(thisURL!.lastPathComponent)"


    }
 }
like image 338
spa0201su Avatar asked Apr 21 '20 10:04

spa0201su


People also ask

How do you read and write files in Swift?

Fundamentally, there are two Foundation types that are especially important when reading and writing files in Swift — URL and Data. Just like when performing network calls, URLs are used to point to various locations on disk, which we can then either read binary data from, or write new data into.

How do I access the main bundle in Swift?

That main bundle can be accessed using Bundle.main, which lets us retrieve any resource file that was included within our main app target, such as a bundled JSON file, like this: struct ContentLoader { enum Error: Swift.

How do I import a swift target with spaces?

If a Swift target has a space in its name, you can import it by replacing the spaces with underscores in the import statement. "My Swift Class" becomes "My_Swift_Class".


Video Answer


2 Answers

I have done the same thing earlier, Please refer below steps and code:

  1. Create a file URL to the temporary folder

     var tempURL = URL(fileURLWithPath: NSTemporaryDirectory())          
    
  2. Append filename and extension to URL

     tempURL.appendPathComponent(url.lastPathComponent)
    
  3. If the file with the same name exists remove it (replace a file with the new one)

Full Code:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    let newUrls = urls.flatMap { (url: URL) -> URL? in

        var tempURL = URL(fileURLWithPath: NSTemporaryDirectory())          
        tempURL.appendPathComponent(url.lastPathComponent)
        do {

            if FileManager.default.fileExists(atPath: tempURL.path) {
                try FileManager.default.removeItem(atPath: tempURL.path)
            }
            try FileManager.default.moveItem(atPath: url.path, toPath: tempURL.path)
            return tempURL
        } catch {
            print(error.localizedDescription)
            return nil
        }
    }
}
like image 163
Hitesh Surani Avatar answered Sep 22 '22 17:09

Hitesh Surani


Full credit to @COVID19 for the answer though in my case using UIDocumentPickerViewController put the file in the temp folder already and some may like to place it in the documents directory. This is a way of going about that with a single file being selected.

        guard let url = urls.first else { return }

        var newURL = FileManager.getDocumentsDirectory()
        newURL.appendPathComponent(url.lastPathComponent)
        do {
        if FileManager.default.fileExists(atPath: newURL.path) {
            try FileManager.default.removeItem(atPath: newURL.path)
        }
        try FileManager.default.moveItem(atPath: url.path, toPath: newURL.path)
            print("The new URL: \(newURL)")
        } catch {
            print(error.localizedDescription)
        }

and my handy helper method

extension FileManager {

   static func getDocumentsDirectory() -> URL {
       let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
       let documentsDirectory = paths[0]
       return documentsDirectory
   }
}
like image 42
Waylan Sands Avatar answered Sep 22 '22 17:09

Waylan Sands