insert data into plist in swift

Here's how you can insert data into a plist file in Swift:

  1. First, locate the path for your plist file. You can use the following code to get the path:

    main.swift
    guard let path = Bundle.main.path(forResource: "yourPlistFileName", ofType: "plist") else { return }
    
    101 chars
    2 lines
  2. Load the content of your plist file into an NSMutableDictionary

    main.swift
    let plistData = NSDictionary(contentsOfFile: path)
    let mutablePlistData = plistData?.mutableCopy() as? NSMutableDictionary ?? NSMutableDictionary()
    
    148 chars
    3 lines
  3. Insert data into the NSMutableDictionary

    main.swift
    mutablePlistData.setValue("Your value", forKey: "Your key")
    
    60 chars
    2 lines
  4. Write the updated NSMutableDictionary contents back to your plist file

    main.swift
    mutablePlistData.write(toFile: path, atomically: true)
    
    55 chars
    2 lines

Here's the complete code:

main.swift
guard let path = Bundle.main.path(forResource: "yourPlistFileName", ofType: "plist") else { return }

let plistData = NSDictionary(contentsOfFile: path)
let mutablePlistData = plistData?.mutableCopy() as? NSMutableDictionary ?? NSMutableDictionary()

mutablePlistData.setValue("Your value", forKey: "Your key")

mutablePlistData.write(toFile: path, atomically: true)
367 chars
9 lines

gistlibby LogSnag