获取文档目录收件箱文件并移动

时间:2015-12-29 15:11:43

标签: ios swift swift2 nsurl nsfilemanager

我的应用程序中有一个传入的PDF附件。它是NSURL分配的AppDelegate

func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {

该文件以print日志打印为:

  

传入文件:   文件:///private/var/mobile/Containers/Data/Application/65E4F19F-98DD-4A4E-8A49-E1C564D135D8/Documents/Inbox/Burrito.pdf

如何将文件从DocumentDirectory Inbox文件夹中取出,默认情况下该文件放在传入文件中?我试图创建一个名为" Recipes"的新文件夹。然后将其移动到此文件夹,但它不会收到错误:

  

无法创建目录错误域= NSCocoaErrorDomain代码= 516   "“Burrito-2.pdf”无法移动到“文档”,因为有一个项目   同名已经存在。"   的UserInfo = {NSSourceFilePathErrorKey = /私有的/ var /移动/容器/数据/应用/ D5C9B472-B880-4D68-BA0D-31BA545E2150 /文档/收件箱/ Burrito.pdf,   NSUserStringVariant =(       移动),NSDestinationFilePath = / var / mobile / Containers / Data / Application / D5C9B472-B880-4D68-BA0D-31BA545E2150 / Documents / Recipes,   NSFilePath = /私有的/ var /移动/容器/数据/应用/ D5C9B472-B880-4D68-BA0D-31BA545E2150 /文档/收件箱/ Burrito.pdf,   NSUnderlyingError = 0x13912e0e0 {错误域= NSPOSIXErrorDomain代码= 17   "文件存在"}}

移动文件的代码是:

    // Incoming file
    print("Incoming File: \(incomingFileTransfer)")

    // File Manager
    let filemgr = NSFileManager.defaultManager()

    // Document Directory
    var dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)

    // Documents Location
    let docsDir = dirPaths[0] //as! String
    print("Documents Folder: \(docsDir)")

    print("------------------------")

    // Create a new folder in the directory named "Recipes"
    print("Creating new folder...")
    let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
    let newPath = documentsPath.URLByAppendingPathComponent("Recipes")
    do {
        try NSFileManager.defaultManager().createDirectoryAtPath(newPath.path!, withIntermediateDirectories: true, attributes: nil)
    } catch let error as NSError {
        NSLog("Unable to create directory \(error.debugDescription)")
    }
    print("New Path: \(newPath)")
    print("------------------------")


    // Moving item in folder
    print("Moving PDf file to new folder...")

    let startingPath = incomingFileTransfer
    let endingPath = newPath

    do {
       try filemgr.moveItemAtURL(startingPath, toURL: endingPath)
    } catch let error as NSError {
        NSLog("Unable to create directory \(error.debugDescription)")
    }

我是Swift的新手,已经在线研究和文件管理文档,但无法解决这个问题。我看了here,但它不同,也在Objective-C;转换为Swift对我来说很难。我使用Xcode7Swift2,谢谢。

1 个答案:

答案 0 :(得分:2)

第二次运行应用程序并且已创建目录且文件已被移动时,会出现错误。

Apple强烈建议您使用与NSFileManager

相关的网址API

首先获取文件目录

// File Manager
let filemgr = NSFileManager.defaultManager()

// Document Directory
let docsDirURL = try! filemgr.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)

try!语句是安全的,因为文档目录始终存在。

然后检查Recipes目录是否存在。如果没有,请创建

let recipesURL = docsDirURL.URLByAppendingPathComponent("Recipes")
if !filemgr.fileExistsAtPath(recipesURL.path!) {
  do {
    try filemgr.createDirectoryAtURL(recipesURL, withIntermediateDirectories: false, attributes: nil)
    print("Directory created at: \(recipesURL)")
  } catch let error as NSError {
    NSLog("Unable to create directory \(error.debugDescription)")
    return
  }
}

您还可以检查目标文件是否存在

let incomingFileName = incomingFileTransfer.lastPathComponent!

let startingURL = incomingFileTransfer
let endingURL = recipesURL.URLByAppendingPathComponent(incomingFileName)

if !filemgr.fileExistsAtPath(endingURL.path!) {
  do {
    try filemgr.moveItemAtURL(startingURL, toURL: endingURL)
  } catch let error as NSError {
    NSLog("Unable to move file \(error.debugDescription)")
  }
}