我有一个阻止用户访问视图控制器几行的应用程序。通过检查是否将bool类型的变量设置为true或false来完成此操作。

//variable to see if user has purchased the IAP
var unlocked: Bool = false

//formatting the cells that display the sections
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!

    //blocking cells if the are not paid for.
    if unlocked == false {

        if ( indexPath.row  >= 2 ) {
            cell.userInteractionEnabled = false
            cell.contentView.alpha = 0.5
        }
        else{
            cell.userInteractionEnabled = true
            cell.contentView.alpha = 1
        }
    } else {
        //unlocking all cells once the unloced variable has been set to true.
        cell.userInteractionEnabled = true
        cell.contentView.alpha = 1
    }

    return cell
}

这很完美。然后,我可以选择让用户购买对其余行的访问权限,从而购买应用程序的其余内容。购买了应用内购买后,它将运行函数“updateSections()”。我知道此功能是在购买时调用的,因为我已经对其进行了测试。

我现在想使用NSUserDefaults保存“解锁”变量的值。这是我所做的:
//function Called once IAP has been made, This unlocks all sections.
func unlockSections() {
    print("Thhe IAP worked")
    //This is the code for what happens once the device has bought the IAP. going to have to save what happens here in using nsuserdefaults to make sure it will work when the app opens and closes.
     unlocked = true
    tableview.reloadData()

//saving unlocked status
let defaults =  NSUserDefaults.standardUserDefaults()
defaults.setBool(unlocked, forKey: "unlockedStatus")

}

为了阅读它,然后当用户关闭并重新打开应用程序时,我将其放在viewDidLoad中:
//Reading saved unlocked value. ensure that purches are restored for when device is offline.
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.stringForKey("unlockedStatus")

我也尝试过将它放在viewDidAppear中,但这也不起作用。我似乎找不到我要去哪里。有人能看到我要去哪里了吗?

最佳答案

您正在保存布尔值并检索字符串值。
因此,而不是检索布尔值。
用这个

let defaults = NSUserDefaults.standardUserDefaults()
defaults.boolForKey("unlockedStatus")

希望这会帮助你。

关于ios - NSUserDefaults保存。编码问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41827796/

10-11 22:14
查看更多