如何使用 Plist 数据验证来自 UItextfield 的用户输入

How to validate user input from UItextfield with Plist data

我有一个包含用户名和密码的 Plist 文件。

在Objective-C

你可以试试

Swift

// 强制展开以确保数据存在

let path = Bundle.main.path(forResource: "fileName", ofType: "plist")  

let dic = NSDictionary(contentsOfFile: path) as! [String:String]  

self.name = dic["username"] as! String

self.pass = dic["password"] as! String

提交时

检查

if username.text == name && password.text == pass {
    // success
}

Objective-C

NSDictionary *mainDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"plist"]];

NSString *name = mainDictionary[@"username"];

NSString *pass = mainDictionary[@"password"];

if ([username.text isEqualToString:name] && [password.text isEqualToString:pass]) {

     // success
}

通过

获取 plist 是安全的
func getDictOfPlist(fileName : String) -> [String:String]? {
    guard let filePath = Bundle.main.path(forResource: fileName, ofType: "plist") else {
        // can't gen file path
        return nil
    }
    guard let dict = NSDictionary(contentsOfFile: filePlist) as? [String:String] else {
        // can't read file or data type false
        return nil
    }
    return dict
}

用于

    if let content = getDictOfPlist(fileName: "UserData") {
        username.text = content["name"]
        // ....
        // ....
    }