gpt4 book ai didi

swift - 如何快速移动文件

转载 作者:行者123 更新时间:2023-12-04 15:59:39 26 4
gpt4 key购买 nike

在使用 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)"


}
}

最佳答案

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

  • 创建临时文件夹的文件 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
    }
    }
    }

    关于swift - 如何快速移动文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61341061/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com