Как переместить файл в swift - PullRequest
0 голосов
/ 21 апреля 2020

Я пытаюсь переместить файл в каталог документов после выбора файла с помощью UIDocumentPickerViewController.

Я не вижу ошибок, но файл не перемещается в каталог.

Я хотел бы знать, как я могу переместить файл.

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)"


    }
 }

Ответы [ 2 ]

1 голос
/ 21 апреля 2020

Я делал то же самое ранее, пожалуйста, следуйте инструкциям и коду ниже:

  1. Создайте URL-адрес файла для временной папки

    var tempURL = URL(fileURLWithPath: NSTemporaryDirectory())          
    
  2. Добавить имя файла и расширение к URL

    tempURL.appendPathComponent(url.lastPathComponent)
    
  3. Если файл с таким именем существует, удалить его (заменить файл новым)

Полный код:

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
        }
    }
}
0 голосов
/ 24 апреля 2020

Полный кредит @ COVID19 за ответ, хотя в моем случае с помощью UIDocumentPickerViewController уже поместите файл во временную папку, и некоторые могут захотеть поместить его в каталог документов. Это способ сделать это с одним выбранным файлом.

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

и мой удобный вспомогательный метод

extension FileManager {

   static func getDocumentsDirectory() -> URL {
       let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
       let documentsDirectory = paths[0]
       return documentsDirectory
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...