如何在Swift中移动文件

8

我正在尝试使用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)"


    }
 }

1
我没有看到任何错误,显然是因为奇怪的缩进导致代码甚至没有编译成功。 - vadian
为了让人们能够回答您的问题,请格式化您的代码以使其易读。 - Ashley Mills
2个回答

13

我之前也做过同样的事情,请参考以下步骤和代码:

  1. 创建到临时文件夹的文件URL

 var tempURL = URL(fileURLWithPath: NSTemporaryDirectory())          
  • 将文件名和扩展名添加到URL中

  •  tempURL.appendPathComponent(url.lastPathComponent)
    
  • 如果同名文件已经存在,则删除它(用新文件替换旧文件)

  • 完整代码:

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

    3

    虽然这个答案全部归功于@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
       }
    }
    

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接