使用swift检查CloudKit中是否存在具有指定值的记录

问题描述 投票:2回答:2

我有个问题。我正在做一个具有登录功能的应用程序,并希望检查是否存在具有指定用户名的用户。所以我做了:

func doesRecordExist(inRecordType: String, withField: String, equalTo: String) -> Bool {
    print(withField,equalTo)
    var result = false

    let predicate = NSPredicate(format: "\(withField) == %@", equalTo)
    let query = CKQuery(recordType: inRecordType, predicate: predicate)
    publicDatabase.perform(query, inZoneWith: nil, completionHandler: {results, er in

        if results != nil {
            print(results!.count)
            if results?.count == 1 {
                print(results!.count)
                result = true
            }
        }
    })
    return result
}

在哪里输入whitField“username”并且等于输入将输入的用户名。

我做错了什么?谢谢。

编辑 好吧,我终于想出了如何做rmaddy建议并且它有效。非常感谢你!

swift cloudkit
2个回答
0
投票

如果该函数的结果取决于异步操作的结果,则无法从函数返回值。如上所述,函数末尾的return result行(值为false)将在数据库查询开始之前很久就被调用。

你的doesRecordExist函数需要使用perform函数的多行完成处理程序参数。

当然,你需要重构你的代码,调用你的doesRecordExist来处理你不会立即获得立即结果的事实。


0
投票

以下是您的代码转换为根据rmaddy的响应添加完成处理程序,因为这应该让您的代码在继续下一个代码之前等待结果。

func doesRecordExist(inRecordType: String, withField: String, equalTo: String, _ completion: @escaping (Bool) -> ()) {
    print(withField,equalTo)
    var result = false

    let predicate = NSPredicate(format: "\(withField) == %@", equalTo)
    let query = CKQuery(recordType: inRecordType, predicate: predicate)
    publicDatabase.perform(query, inZoneWith: nil, completionHandler: {results, er in

        if results != nil {
            print(results!.count)
            if results?.count == 1 {
                print(results!.count)
                result = true
            }
        }
    })
    completion(result)
}

然后在其他位置运行代码:

doesRecordExist(inRecordType: String, withField: String, equalTo: String) { (result) in
                    if result == false {
                   //create new record here
                    }
                }
© www.soinside.com 2019 - 2024. All rights reserved.