2017-03-11 45 views
0

Data.plistというファイルを使用して単純な構造化されていないデータを保存しようとしていますが、このファイルをアプリケーションのルートフォルダに配置しました。このファイルを読み書きするのを簡単にするために、私は以下を作成しましたDataManager struct。それは問題なしでData.plistファイルを読むことができますが、ファイルにデータを書き込むことはできません。どこに問題があるのか​​わからない、だれかが間違っているかも知れないのだろうか?Swift 3:plistファイルにデータを書き込むことができません

struct DataManager { 

    static var shared = DataManager()   

    var dataFilePath: String? {   
     return Bundle.main.path(forResource: "Data", ofType: "plist") 
    } 

    var dict: NSMutableDictionary? { 
     guard let filePath = self.dataFilePath else { return nil } 
     return NSMutableDictionary(contentsOfFile: filePath) 
    } 

    let fileManager = FileManager.default 

    fileprivate init() { 

     guard let path = dataFilePath else { return } 
     guard fileManager.fileExists(atPath: path) else { 
      fileManager.createFile(atPath: path, contents: nil, attributes: nil) // create the file 
      print("created Data.plist file successfully") 
      return 
     } 
    } 

    func save(_ value: Any, for key: String) -> Bool { 
     guard let dict = dict else { return false } 

     dict.setObject(value, forKey: key as NSCopying) 
     dict.write(toFile: dataFilePath!, atomically: true) 

     // confirm 
     let resultDict = NSMutableDictionary(contentsOfFile: dataFilePath!) 
     print("saving, dict: \(resultDict)") // I can see this is working 

     return true 
    } 

    func delete(key: String) -> Bool { 
     guard let dict = dict else { return false } 
     dict.removeObject(forKey: key) 
     return true 
    } 

    func retrieve(for key: String) -> Any? { 
     guard let dict = dict else { return false } 

     return dict.object(forKey: key) 
    } 
} 

答えて

1

アプリケーションバンドル内のファイルは変更できません。したがって、Bundle.main.path(forResource:ofType:)で取得するすべてのファイルは読み取り可能ですが、書き込みはできません。

このファイルを変更するには、まずアプリケーションのドキュメントディレクトリ内にコピーする必要があります。

let initialFileURL = URL(fileURLWithPath: Bundle.main.path(forResource: "Data", ofType: "plist")!) 
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! 
let writableFileURL = documentDirectoryURL.appendingPathComponent("Data.plist", isDirectory: false) 

do { 
    try FileManager.default.copyItem(at: initialFileURL, to: writableFileURL) 
} catch { 
    print("Copying file failed with error : \(error)") 
} 

// You can modify the file at writableFileURL 
+0

ありがとうございます、ドキュメントディレクトリにありがとうございます。私はただばかです! :D – TonyGW

関連する問題