2016-02-02 15 views
14

DocumentDirectoryにPDFファイルがあります。DocumentDirectoryのファイル名を変更してください

ユーザーは、このPDFファイルの名前を別のものに変更できるようにしたいと考えています。

私は、このプロセスを開始するUIButtonを持つことになります。新しい名前はUITextFieldから来ます。

どうすればよいですか?私はSwiftには新しく、これに関するObjective-Cの情報しか見つけられておらず、変換に苦労しています。

ファイルの場所の例は次のとおり

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

 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") 

     } 

答えて

20

あなたはNSFileManagerのmoveItemAtURLを使用することができますファイルの名前を変更するには:私は、ファイルが存在するかどうかをチェック表示するには、このコードを持っています。

同じ場所にmoveItemAtURLでファイルを移動するが、2人の異なるファイル名で、「名前の変更」と同じ操作です。

簡単な例:

スウィフト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) 
} 

スウィフト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

私は知りませんでした。私は少しそれを修正し、それは素晴らしい仕事をした。ありがとうございました! – ChallengerGuy

+0

ようこそ。 – Moritz

+0

Swift 3の例を追加してください。 Thx –

6

任意のNSURLでアイテムの名前を変更する簡単な方法があります。

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

ベスト・アンサー!ありがとうございました! – rmvz3

+0

UbiquityContainer URLでも同様に動作します。あなたは歓迎です:) –

+1

今は廃止されたようです。 'url.setTemporaryResourceValue(newName、forKey:.nameKey)'を使用してください。 –

関連する問題