Swift 2 iOS 9: Plist Reading and Writing

二次信任 提交于 2019-12-23 12:36:47

问题


I believe something has changed within Swift 2, because no tutorials on how to read and write to property lists seem to be working.

Can anyone whose developing for iOS 9 share their method of R/W to Plists using Swift 2 on Xcode 7?


回答1:


This is working for me on iOS 9 and Xcode 7:

let filePath = NSBundle.mainBundle().pathForResource("FileName", ofType: "plist")!    
let stylesheet = NSDictionary(contentsOfFile:filePath)

The only thing is that the result is NSDictionary and not Dictionary.




回答2:


Hopefully this is helpful - without code it is difficult to answer.

The change that tripped me up is that when copying a plist file over to the documents directory the method stringByAppendingPathComponent is no longer available. You have to use NSURL instead.

If you have a preparePlistForUseMethod it should now look like this.

let rootPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0]
        let url = NSURL(string: rootPath)
        plistPathInDocument = (url?.URLByAppendingPathComponent("plistfilename.plst").absoluteString)!

if !NSFileManager.defaultManager().fileExistsAtPath(plistPathInDocument){
            let plistPathInBundle = NSBundle.mainBundle().pathForResource("plistfilename.plst", ofType: "plist")!

            do{
            try NSFileManager.defaultManager().copyItemAtPath(plistPathInBundle, toPath: plistPathInDocument)
                print("plist copied")
            }
            catch{
                print("error copying plist!")
            }
        }
        else{
            print("plst exists \(plistPathInDocument)")
    }
}



回答3:


For reading on a PLIST, I encapsulated the logic in a Singleton. In my case, I want to read the file URLs.plist.

class URLs {

    class var sharedInstance: URLs {
        struct Singleton {
            static let instance = URLs()
        }
        return Singleton.instance
    }

    private var urls: NSDictionary!

    required init() {
        let filePath = NSBundle.mainBundle().pathForResource("URLs", ofType: "plist")!
        self.urls = NSDictionary(contentsOfFile:filePath)
    }

    var backendBaseUrl: String {
        get {
            return urls["BackendBaseUrl"] as! String
        }
    }

    var locationEndpoint: String {
        get {
            return urls["LocationEndpoint"] as! String
        }
    }

}

Wherever you need to access one of those URLs, you just:

URLs.sharedInstance.backendBaseUrl

This works fine with Xcode 7.1 and Swift 2.1.



来源:https://stackoverflow.com/questions/31688761/swift-2-ios-9-plist-reading-and-writing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!