2016-05-21 14 views
0

Wie kann ich den gesamten Inhalt eines Ordners mit Swift auf einem OS X kopieren und einfügen? Wenn der Zielpfad den Ordner bereits enthält, sollte er ihn ersetzen.Ersetzen Sie Ordner im Dateisystem mit Swift

Ich versuchte

let appSupportSourceURL = NSURL(string: appSupportSourcePath) 
     let appSupportDestinationURL = NSURL(string: appSupportDestinationPath+"/"+appSupportFileName) 

     if (fileManager.isReadableFileAtPath(appSupportSourcePath)){ 
      do { 
      try fileManager.copyItemAtURL(appSupportSourceURL!, toURL: appSupportDestinationURL!)} 
      catch{ 
      } 
     } 

aber ich erkennen, dass dies nur für Dateien funktioniert. Ich versuche, einen ganzen Ordner zu ersetzen.

Antwort

1

Ich weiß, Apple ermutigt neuen Code, die URLs zu verwenden, um Dateisystempfad anzugeben. NSFileManager ist jedoch eine alte Klasse und befindet sich immer noch im Übergang zwischen dem alten stringbasierten Pfad und dem neuen URL-basierten Paradigma. Versuchen Sie folgendes:

let appSupportSourcePath = "..." 
let appSupportDestinationPath = "..." 

let fileManager = NSFileManager.defaultManager() 
do { 
    // Delete if already exists 
    if fileManager.fileExistsAtPath(appSupportDestinationPath) { 
     try fileManager.removeItemAtPath(appSupportDestinationPath) 
    } 
    try fileManager.copyItemAtPath(appSupportSourcePath, toPath: appSupportDestinationPath) 

} catch { 
    print(error) 
} 

Edit: Methode mit NSURL

let appSupportSourceURL = NSURL(fileURLWithPath: "...", isDirectory: true) 
let appSupportDestionURL = NSURL(fileURLWithPath: "...", isDirectory: true) 

try! NSFileManager.defaultManager().copyItemAtURL(appSupportSourceURL, toURL: appSupportDestionURL)