如何使用plist保存数组Swift中的用户进度

时间:2015-08-21 21:35:16

标签: ios swift nsuserdefaults

嘿,在我的应用程序中,用户单击一个名为showfunfact()的按钮,通过一个字符串数组移动它们。当用户从多任务处理中移除应用程序或关闭手机时,我希望用户可以保存该位置,然后在重新加载时可以从他们停止的地方继续使用

var TechfactIndex = 0
let TechnologyfactBook = TechFactBook()

override func viewDidLoad() {
    super.viewDidLoad()
    let defaults = NSUserDefaults.standardUserDefaults()
    TechfactIndex = NSUserDefaults.standardUserDefaults().integerForKey("ByteLocation")
    defaults.setObject(TechfactIndex, forKey: "ByteLocation")
}

@IBAction func showFunFact() {
    if ( UIApplication.sharedApplication().applicationIconBadgeNumber != 0){
        UIApplication.sharedApplication().applicationIconBadgeNumber = 0
    }

    if (TechfactIndex >= TechnologyfactBook.TechfactsArray.count) {  
        self.TechfactIndex = 0   
    }

    TechByteLabel.text = TechnologyfactBook.TechfactsArray[TechfactIndex]
    TechfactIndex++
}

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    NSUserDefaults.standardUserDefaults().setInteger(TechfactIndex, forKey: "ByteLocation")
    NSUserDefaults.standardUserDefaults().synchronize()
}

2 个答案:

答案 0 :(得分:2)

问题是viewDidDisappear:与您的规范无关。它没有被调用"当用户从多任务中删除应用程序或关闭手机时#34;。电话响铃时不会呼叫。当用户点击主页按钮时不会调用它。这无关紧要。您已将代码放在错误的位置。

您要做的是注册,以便在应用停用时听到。这是将信息写入用户默认值的时刻。

答案 1 :(得分:1)

每次查看下一个有趣的事实时,只需写入用户默认值就不会那么昂贵。因此,为了简单起见,您可以在每次查看新的有趣事实时将新索引写入NSUserDefaults

@IBAction func showFunFact() {
    if (UIApplication.sharedApplication().applicationIconBadgeNumber != 0){
        UIApplication.sharedApplication().applicationIconBadgeNumber = 0
    }

    TechfactIndex = NSUserDefaults.standardUserDefaults().integerForKey("ByteLocation")

    if (TechfactIndex >= TechnologyfactBook.TechfactsArray.count) {  
        self.TechfactIndex = 0   
    }

    TechByteLabel.text = TechnologyfactBook.TechfactsArray[TechfactIndex]
    TechfactIndex++
    NSUserDefaults.standardUserDefaults().setInteger(TechfactIndex, forKey: "ByteLocation")
    NSUserDefaults.standardUserDefaults().synchronize()
}

但是,用户默认值通常是为首选项保留的...所以你可能最好在这里实现一个plist(或类似的简单保存选项)来存储当前索引。

编辑:以下是一个关于如何使用plist实现此目的的简单示例

首先,在目录中创建一个Property List文件,将其命名为Data.plist。使根对象成为字典,并使用键FunFactIndex添加NSNumber对象。这将是第一次保存时plist的模板。

func showFunFact() {
    if (UIApplication.sharedApplication().applicationIconBadgeNumber != 0){
        UIApplication.sharedApplication().applicationIconBadgeNumber = 0
    }

    // Load the next index
    var factIndex = getCurrentFunFactIndex() as Int

    if factIndex < 0 {
        println("error")
        return
    }

    if (factIndex >= TechnologyfactBook.TechfactsArray.count) {
        factIndex = 0
    }

    TechByteLabel.text = TechnologyfactBook.TechfactsArray[factIndex]
    factIndex++

    // Save the index
    let saveSuccess = saveFunFactIndex(factIndex);

    let successString = (saveSuccess) ? "success" : "failure"

    println("Save was a \(successString)")
}

func getCurrentFunFactIndex() -> Int {

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

    let fileManager = NSFileManager.defaultManager()

    // Check if file exists, copy it over from the bundle if it doesn't
    if !fileManager.fileExistsAtPath(path) {
        let bundle = NSBundle.mainBundle().pathForResource("Data", ofType: "plist")
        fileManager.copyItemAtPath(bundle!, toPath: path, error:nil)
    }

    if let dataDict = NSDictionary(contentsOfFile: path) {
        if let indexNum: AnyObject = dataDict.objectForKey("FunFactIndex") {
            return indexNum.integerValue
        }
    }

    return -1   // Something went wrong
}

func saveFunFactIndex(index: Int) -> Bool {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths.objectAtIndex(0) as! NSString
    let path = documentsDirectory.stringByAppendingPathComponent("Data.plist")

    let fileManager = NSFileManager.defaultManager()

    // Check if file exists, copy it over from the bundle if it doesn't
    if !fileManager.fileExistsAtPath(path) {
        let bundle = NSBundle.mainBundle().pathForResource("Data", ofType: "plist")
        fileManager.copyItemAtPath(bundle!, toPath: path, error:nil)
    }

    if let dataDict = NSMutableDictionary(contentsOfFile: path) {
        let indexNum: NSNumber = index
        dataDict.setObject(indexNum, forKey: "FunFactIndex")
        return dataDict.writeToFile(path, atomically: true)
    }

    return false
}

我为你添加了两种方法;文档目录中的getCurrentFunFactIndexsaveFunFactIndex:. Both will first check in the Documents directory of the sandbox for Data.plist . If that file does not exist, it will copy over the template plist that we created in the bundle. All future uses of these methods will use the Data.plist`文件。这将允许该值在后续应用程序启动时保留(从后台删除应用程序或关闭设备)。