2016-02-02 5 views
14

में फ़ाइल का नाम बदलें मेरे पास मेरे DocumentDirectory में एक पीडीएफ फ़ाइल है।दस्तावेज़ डायरेक्टरी

मैं चाहता हूं कि उपयोगकर्ता इस पीडीएफ फाइल का नाम बदलने के लिए कुछ और करने में सक्षम हो।

इस प्रक्रिया को शुरू करने के लिए मेरे पास UIButton होगा। नया नाम UITextField से आएगा।

मैं यह कैसे कर सकता हूं? मैं स्विफ्ट के लिए नया हूं और केवल इस पर उद्देश्य-सी जानकारी पाई है और मुझे इसे बदलने में कठिनाई हो रही है।

फ़ाइल स्थान का एक उदाहरण है:

/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

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

कृपया एक स्विफ्ट 3 उदाहरण जोड़ें। Thx –

6

किसी भी NSURL में आइटम का नाम बदलने के लिए एक आसान तरीका है।

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

सबसे अच्छा जवाब! धन्यवाद! – rmvz3

+0

UbiquityContainer URL पर भी काम करता है। आपका स्वागत है :) –

+1

ऐसा लगता है कि यह अब बहिष्कृत है। उपयोग करें: 'url.setTemporaryResourceValue (newName, forKey: .nameKey) ' –

संबंधित मुद्दे