2016-02-02 10 views
14

Ho un file PDF nel mio DocumentDirectory.Rinomina file in DocumentDirectory

Desidero che l'utente sia in grado di rinominare questo file PDF in qualcos'altro se lo desidera.

Avrò un UIButton per iniziare questo processo. Il nuovo nome verrà da UITextField.

Come posso fare? Sono nuovo di Swift e ho trovato solo informazioni su Objective-C e sto avendo difficoltà a convertirlo.

Un esempio del percorso del file è:

/var/mobile/Containers/Data/Application/39E030E3-6DA1-45FF-BF93-6068B3BDCE89/Documents/Restaurant.pdf

ho questo codice per vedere verificare se il file esiste o no:

 var name = selectedItem.adjustedName 

     // Search path for file name specified and assign to variable 
     let getPDFPath = paths.stringByAppendingPathComponent("\(name).pdf") 

     let checkValidation = NSFileManager.defaultManager() 

     // If it exists, delete it, otherwise print error to log 
     if (checkValidation.fileExistsAtPath(getPDFPath)) { 

      print("FILE AVAILABLE: \(name).pdf") 

     } else { 

      print("FILE NOT AVAILABLE: \(name).pdf") 

     } 

risposta

20

per rinominare un file è possibile utilizzare NSFileManager di moveItemAtURL.

Spostare il file con moveItemAtURL nella stessa posizione ma con due nomi di file diversi è la stessa operazione di "ridenominazione".

semplice esempio:

Swift 2

do { 
    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] 
    let documentDirectory = NSURL(fileURLWithPath: path) 
    let originPath = documentDirectory.URLByAppendingPathComponent("currentname.pdf") 
    let destinationPath = documentDirectory.URLByAppendingPathComponent("newname.pdf") 
    try NSFileManager.defaultManager().moveItemAtURL(originPath, toURL: destinationPath) 
} catch let error as NSError { 
    print(error) 
} 

Swift 3

do { 
    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] 
    let documentDirectory = URL(fileURLWithPath: path) 
    let originPath = documentDirectory.appendingPathComponent("currentname.pdf") 
    let destinationPath = documentDirectory.appendingPathComponent("newname.pdf") 
    try FileManager.default.moveItem(at: originPath, to: destinationPath) 
} catch { 
    print(error) 
} 
+0

Non lo sapevo. L'ho modificato un po 'e ha funzionato alla grande. Grazie! – ChallengerGuy

+0

Prego. – Moritz

+0

per favore aggiungi un esempio Swift 3. Thx –

6

C'è un modo più semplice per rinominare voce in un dato NSURL.

url.setResourceValue(newName, forKey: NSURLNameKey) 
+0

La migliore risposta !. Grazie! – rmvz3

+0

Funziona anche con gli URL UbiquityContainer. Siete i benvenuti :) –

+1

Sembra che ora sia deprecato. Usa: 'url.setTemporaryResourceValue (newName, forKey: .nameKey)' –