spa0201su
spa0201su

Reputation: 125

How to move a file in 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)"


    }
 }

Upvotes: 9

Views: 7160

Answers (2)

Waylan Sands
Waylan Sands

Reputation: 375

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
   }
}

Upvotes: 3

Hitesh Surani
Hitesh Surani

Reputation: 13537

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
        }
    }
}

Upvotes: 13

Related Questions