How to read and save data from a remote plist file
Asked Answered
L

2

11

I need help to read and write data to a remote plist file in my iOS application with Swift. I can read and save data in local but not with a remote server.

Here, my code to read in local.

Variables

    var VintiInizialiID: AnyObject!
    var PersiInizialiID: AnyObject!
    var CampionatoID: AnyObject!
    var coefficientetorneoID: AnyObject!

loadPlistData()

func loadPlistData() {

    var VintiInizialiKey = "VintiIniziali"
    var PersiInizialiKey = "PersiIniziali"
    var TutorialKey = "Tutorial"
    var coefficientetorneoKey = "CoefficienteTorneo"
    var CampionatoKey = "Campionato"


    // getting path to database.plist
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths[0] as! String
    let path = documentsDirectory.stringByAppendingPathComponent("database.plist")

    let fileManager = NSFileManager.defaultManager()

    //check if file exists
    if(!fileManager.fileExistsAtPath(path)) {
        // If it doesn't, copy it from the default file in the Bundle
        if let bundlePath = NSBundle.mainBundle().pathForResource("database", ofType: "plist") {

            let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
            println("Bundle database.plist file is --> \(resultDictionary?.description)")

            fileManager.copyItemAtPath(bundlePath, toPath: path, error: nil)
            println("copy")
        } else {
            println("database.plist not found. Please, make sure it is part of the bundle.")
        }
    } else {
        println("database.plist already exits at path.")
        // use this to delete file from documents directory
        //fileManager.removeItemAtPath(path, error: nil)
    }

    let resultDictionary = NSMutableDictionary(contentsOfFile: path)
    println("Loaded database.plist file is --> \(resultDictionary?.description)")

    var myDict = NSDictionary(contentsOfFile: path)

    if let dict = myDict {
        //loading values
        VintiInizialiID = dict.objectForKey(VintiInizialiKey)!
        PersiInizialiID = dict.objectForKey(PersiInizialiKey)!
                     CampionatoID = dict.objectForKey(CampionatoKey)!
       coefficientetorneoID = dict.objectForKey(coefficientetorneoKey)!


        //...
    } else {
        println("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")
    }
}

And Finally SavePlistData()

func Saveplistdata()  {



    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths.objectAtIndex(0)as! NSString
    let path = documentsDirectory.stringByAppendingPathComponent("database.plist")

    var dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]
    //saving values
    dict.setObject(VintiInizialiID, forKey: "VintiIniziali")
    dict.setObject(PersiInizialiID, forKey: "PersiIniziali")
    dict.setObject(CampionatoID, forKey: "Campionato")
    dict.setObject(coefficientetorneoID, forKey: "CoefficienteTorneo")

    //...

    //writing to database.plist
    dict.writeToFile(path, atomically: false)

    let resultDictionary = NSMutableDictionary(contentsOfFile: path)
   // println("Saved database.plist file is --> \(resultDictionary?.description)")
}
Lobo answered 30/8, 2015 at 9:25 Comment(4)
What exactly you need help with? Can you be more specific regarding the "remote server"?Pasley
I mean: on my remore domain there's a plist file. How can i read and save informations here?Lobo
I'm not sure using a plist stored on a remote server is the right choice here. There will be many issues to deal with if you have more than one person doing this. If you want to go this route, download the file locally, change it locally, and then upload to the server. However, there are many alternatives available to you for remote configuration like CloudKit, Parse, or similar.Compo
I think @ScottH is ultimately correct. I only opened a bounty on this question to receive the Investor badge. Though I was curious if someone could come up with some crafty way of pulling this off. Truth is, a plist is a poor choice for serious persistence. Look into Parse, it has a really friendly API.Winna
W
5

No, there isn't a native way to read and write to an external .plist using just Swift without downloading the file, making changes and re-uploading it. Alternatively, you'd need to set up your own API on a server in order to carry out the read / write actions for you.

As @Scott H stated in the comments, theres a better way to do this:

If you want to go this route, download the file locally, change it locally, and then upload to the server. However, there are many alternatives available to you for remote configuration like CloudKit, Parse, or similar.

Learn more about 3rd party options:

Winna answered 6/10, 2015 at 12:2 Comment(1)
Thank you, have a nice day.Lobo
B
-2

NSMutableDictionary(contentsOfFile: bundlePath)

Use contentsOfURL instead.

Bolzano answered 6/10, 2015 at 4:4 Comment(2)
No, people are editing your post because you shouldn't add commentary to the body of your post, if you have commentary, put it where its supposed to go, in the comments... I apologize if I offended you, I may have been out of line, however this confusion could have been avoided if you would have followed Stack Overflows answering guide-line in: How to Answer.Winna
btw, nothing on stack overflow can be hidden. Stack overflow saves every version of every post (and comment). Just click edit on your post and you can view the revision historyWinna

© 2022 - 2024 — McMap. All rights reserved.