简体   繁体   English

如何使用联系人框架保存联系人

[英]How to save contacts using Contacts framework

in my app i am saving contacts on event of button click. 在我的应用程序中,如果单击按钮,我将保存联系人。 so on cthe click of button its saving appropriate contact. 如此单击按钮即可保存适当的联系人。 but when i tried to press another button instead of saving that data its showing error of dulicate contact. 但是,当我尝试按下另一个按钮而不是保存该数据时,它显示了双重联系错误。 so how can i solve this? 那么我该如何解决呢?

here is my code 这是我的代码

let fooBar = CNMutableContact()
var store = CNContactStore()

in cellforrow at indexpath 在cellforrow在indexpath

cell.btnClick.tag = indexPath.row
    cell.btnClick.addTarget(self, action: #selector(ViewController.buttonInsertPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)


func buttonInsertPressed(sender:UIButton) {

    getData()
    let index = sender.tag

    print(fooBar)
    phone  = dic.valueForKey("mobile").objectAtIndex(index) as! String

    print(phone)
    //   fooBar.givenName = dic.valueForKey("name").objectAtIndex(indexPath.row) as! String
    let name : String = dic.valueForKey("name").objectAtIndex(index) as! String
    print(fooBar.givenName)
    let homePhone = CNLabeledValue(label: CNLabelHome,
                                   value: CNPhoneNumber(stringValue: phone))

    fooBar.setValue(name, forKey: "givenName")
    fooBar.setValue([homePhone], forKey: "phoneNumbers")
    //   fooBar.phoneNumbers = [homePhone]
    print(fooBar)
            fooBar.middleName = "A."
            fooBar.familyName = "Bar"
    //        fooBar.nickname = "Fooboo"


    if #available(iOS 9.0, *) {
        switch CNContactStore.authorizationStatusForEntityType(.Contacts){
        case .Authorized:
            createContact()
        case .NotDetermined:
            store.requestAccessForEntityType(.Contacts){succeeded, err in
                guard err == nil && succeeded else{
                    return
                }
                self.createContact()
            }
        default:
            print("Not handled")
            if let url = NSURL(string: "tel://\(phone)") {
                UIApplication.sharedApplication().openURL(url)
            }
        }
    } else {
        if let url = NSURL(string: "tel://\(phone)") {
            UIApplication.sharedApplication().openURL(url)
        }
        // Fallback on earlier versions
    }



}


func createContact()
{

    let request = CNSaveRequest()
    request.addContact(fooBar, toContainerWithIdentifier: nil)
    do{
        try store.executeSaveRequest(request)
        print("Successfully stored the contact")
        if let url = NSURL(string: "tel://\(phone)") {
            UIApplication.sharedApplication().openURL(url)
        }




    } catch let err{
        print("Failed to save the contact. \(err)")

        if let url = NSURL(string: "tel://\(phone)") {
            UIApplication.sharedApplication().openURL(url)
        }
    }


}

please let me know how can i solve this? 请让我知道我该如何解决?

Please follow these methods 请遵循以下方法

100% Working Solution 100%工作解决方案

public func askPermissionForContacts(callBack:(Bool)->())
{
    let status : CNAuthorizationStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
    if status == CNAuthorizationStatus.NotDetermined{
        store.requestAccessForEntityType(CNEntityType.Contacts, completionHandler: { (temp: Bool,  error : NSError?) -> Void in
            if temp == true{
               callBack(true)
            }else 
            {
                callBack(false)
            }
        })

    }else if status == CNAuthorizationStatus.Authorized {
        callBack(true)
    }
    else if status == CNAuthorizationStatus.Denied {
        callBack(false)
    }
}



public func createAndSaveContact(userData : AnyObject)
{
    let userDict = userData as! NSDictionary
    let contactNew = CNMutableContact()
    let homePhone = CNLabeledValue(label: CNLabelHome, value: CNPhoneNumber(stringValue: userDict.objectForKey("contact_phone") as! String))
    let homeEmail = CNLabeledValue(label:CNLabelHome, value: userDict.objectForKey("contact_email") as! String)
    contactNew.givenName = userDict.objectForKey("contact_name") as! String
    contactNew.phoneNumbers = [homePhone]
     contactNew.emailAddresses = [homeEmail]
     let request = CNSaveRequest()
    request.addContact(contactNew, toContainerWithIdentifier: nil)
    do{
        try store.executeSaveRequest(request)
        print("Done")

    } catch let err{
        print("Failed to save the contact. \(err)")
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用联系人框架获取 iOS 9 中的所有联系人记录 - How to fetch all contacts record in iOS 9 using Contacts Framework 如何在 iOS 中使用 Contacts Framework 获取更改的联系人 - How to get changed contacts using Contacts Framework in iOS 使用 Safari 保存联系人 - save contacts using safari 如何使用具有长联系人列表的Apple联系人框架更快地获取iOS联系人? - How to fetch iOS Contacts more quickly using Apple's Contacts framework having long list of contacts? 如何使用AddressBook框架但不使用新的Contacts Framework从ABAddressBook iOS获取统一联系人? 可能吗? - How to fetch unified contacts from ABAddressBook iOS using AddressBook framework but by not using new Contacts Framework ? Is it even possible? iOS 联系人框架 - 如何保存/创建新的联系人存储 - iOS Contacts Framework - how to save/create new contact store 如何使用 Contacts with Swift 对联系人进行排序 - How to sort contacts using Contacts with Swift 如何使用 New Contact Framework 查询 IOS 联系人联系人显示订单设置 - How to query IOS Contacts Contacts Display order settings using New Contact Framework 如何使用Swift中的“联系人”框架获取具有手机号码的所有联系人? - How can I get all contacts with a mobile phone number using Contacts framework in Swift? Swift 4.2使用Contacts Framework使用搜索栏搜索联系人 - Swift 4.2 Search contacts with Search Bar using Contacts Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM