【问题标题】:How to list contacts belonging to an iOS group using swift如何使用 swift 列出属于 iOS 组的联系人
【发布时间】:2017-10-17 20:14:19
【问题描述】:

我在 Apple 开发人员文档中找到了以下代码,但我无法理解如何正确调用此函数。非常感谢任何指导。

func fetchContactsInGroup(with identifier: String, completion: @escaping (_ contacts: [CNContact]) -> Void) {
    var result = [CNContact]()
    // Fetch only the full name of a person or organization.
    let request = CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])

    // Predicate to fetch all contacts that are members of the specified group.
    request.predicate = CNContact.predicateForContactsInGroup(withIdentifier: identifier)

    contactStoreQueue.async {
        do {
            try self.store.enumerateContacts(with: request, usingBlock: {(contact, status) -> Void in
                // Add each retured contact to result.
                result.append(contact)
            })
        } catch let error as NSError {
            print("Error \(error.localizedDescription)")
        }

        DispatchQueue.main.async {
            completion(result)
        }
    }
}

【问题讨论】:

  • 你没有得到哪一部分?
  • 调用 func fetchContactsInGroup 的语法 - 完成:位是我的问题

标签: ios iphone swift contacts


【解决方案1】:

好的,从 cmets 看来,您的问题与块有关。调用这个方法最简单的方法是这样的:

fetchContactsInGroup(with: "groupName") { (retrievedContacts:[CNContact]) in
    // your code to proccess retrievedContacts goes here
}

现在,解释一下:这个completion 参数是一个闭包 - 只需将其代码块存储在一个变量中。这是 iOS SDK 中相当常见的模式,因此我鼓励您了解它。这个块被传递,因为该方法本身异步检索联系人。完成后,将调用传递的代码块。重要的是要记住,这可能在未来的任何时间发生。如果在主线程上同步检索联系人,您会觉得您的应用挂起,这很糟糕。
这是一个非常简单的解释,here is a documentation about closures in Swift。我强烈建议您通读它,以及其他有关它的在线教程。如果你之前没有使用过闭包/lambdas,可能不太容易掌握,但你真的应该习惯它。

【讨论】:

  • 它在 [CNContact] 上运行良好,但是我需要更改为我定义的类型并收到此错误 /Users/jeremyandrews/Documents/swift/ARUA Swift 3/ARUA/ControlRoom/ControlRoom/Contacts .swift:72:58:无法转换类型 '(([ContactEntry]?) -> Void).Type' 的值(又名 \'((Optional>) -> ()).Type')到预期的参数类型'([ContactEntry]?) - > Void' 我显然缺少一些东西。非常感谢任何指导
  • 嗯,那是因为您通常无法在两种任意类型之间进行转换。您从系统中检索联系人,系统对您的班级一无所知。您需要在完成块中手动将其从CNContact 转换为ContactEntry
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多