简体   繁体   中英

Why can't I save data in plist file with Swift

** the readData.plist is:**


  <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>currentChapter</key>
    <string>2</string>
    <key>currentLine</key>
    <string>2</string>
    <key>bookname</key>
    <string>ExcelBible</string>
</dict>
</plist>


** The following is code:**


        let Chapter = currentChapter
        let Line = currentLine
        let name = bookname

        let dict:NSMutableDictionary = NSMutableDictionary()



        dict.setObject("1", forKey: "currentChapter" as NSCopying)
        dict.setObject("1", forKey: "currentLine" as NSCopying)
        dict.setObject("WordBible", forKey: "bookname" as NSCopying)

        //I also use dict[0] = "1", and setValue() method both of them are not work

        let plistPath = Bundle.main.path(forResource: "readData", ofType: "plist")

        dict.write(toFile: plistPath!, atomically: true)


Blockquote I also use FileManager and several examples here to save data, some display "Successfully write", but the file does't change.

Blockquote


I am an iOS developer since Feb 12, 2020

I think the file is not in a writable location, so you should create it in the documents directory. Then, it has to be read from the documents directory.

Blockquote

I used the following code, but it does't work too.

Blockquote


let currentChapter = "10"
let currentLine = "10"
let nameOfBook = "WordBible"

let readData = [currentChapter, currentLine, nameOfBook]
//

let dataFilePaths = FileManager.default.urls(for: .documentDirectory,
                                             in: .userDomainMask)[0].appendingPathComponent("gameSave.plist")

let data = try PropertyListEncoder().encode(readData)

try? data.write(to: dataFilePaths, options: Data.WritingOptions.atomic)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM