如何在iOS中的联系人应用程序中保存联系人 - Swift

时间:2016-09-03 17:56:21

标签: ios iphone swift ios9 cncontact

我正在尝试直接使用此代码将联系人保存到联系人应用,而无需请求任何权限:

import Foundation
import UIKit
import Contacts

@available(iOS 9.0, *)
class OnCallEmpContact: UITableViewController {

    var store: CNContactStore!

    @IBOutlet weak var nameLabel: UILabel!

    @IBOutlet weak var phoneLabel: UILabel!

    @IBOutlet weak var emailLabel: UILabel!

    @IBOutlet weak var workPhoneLabel: UILabel!



    var emp = employee()
    var rank = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        self.nameLabel.text=self.emp.getFistName()+" "+emp.getLastName()
        self.phoneLabel.text="0"+self.emp.getMobile()
        self.emailLabel.text=self.emp.getEmail()
        self.workPhoneLabel.text=self.emp.getPhone()

        store = CNContactStore()
        checkContactsAccess()


    }

    private func checkContactsAccess() {
        switch CNContactStore.authorizationStatusForEntityType(.Contacts) {
            // Update our UI if the user has granted access to their Contacts
        case .Authorized:
            self.accessGrantedForContacts()

            // Prompt the user for access to Contacts if there is no definitive answer
        case .NotDetermined :
            self.requestContactsAccess()

            // Display a message if the user has denied or restricted access to Contacts
        case .Denied,
        .Restricted:
            let alert = UIAlertController(title: "Privacy Warning!",
                message: "Permission was not granted for Contacts.",
                preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }

    private func requestContactsAccess() {

        store.requestAccessForEntityType(.Contacts) {granted, error in
            if granted {
                dispatch_async(dispatch_get_main_queue()) {
                    self.accessGrantedForContacts()
                    return
                }
            }
        }
    }

    // This method is called when the user has granted access to their address book data.
    private func accessGrantedForContacts() {
        //Update UI for grated state.
        //...
    }


    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0{
        if rank == "0"{
        return "Primary Employee"
        }
        else if rank == "1"{
        return "Backup Employee"
        }
        }
        return""
    }

    override  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        tableView.deselectRowAtIndexPath(indexPath, animated: true) // to stop highliting the selected cell

        if indexPath.section==1 && indexPath.row==0{
                self.saveContact()
        }


    }



    func saveContact(){
        do{
            let contact = CNMutableContact()
        contact.givenName = self.emp.getFistName()
        contact.familyName = self.emp.getLastName()
        contact.phoneNumbers = [CNLabeledValue(
            label:CNLabelPhoneNumberiPhone,
            value:CNPhoneNumber(stringValue:emp.getMobile())),
                  CNLabeledValue(
                label:CNLabelPhoneNumberiPhone,
                value:CNPhoneNumber(stringValue:emp.getPhone()))]

        let workEmail = CNLabeledValue(label:CNLabelWork, value:emp.getEmail())
        contact.emailAddresses = [workEmail]


        let saveRequest = CNSaveRequest()
        saveRequest.addContact(contact, toContainerWithIdentifier:nil)
        try store.executeSaveRequest(saveRequest)
            print("saved")

        }

        catch{
            print("error")
        }
    }



}

我在方法try store.executeSaveRequest(saveRequest)

的最后一行saveContact收到错误

错误:

  

致命错误:'试试!'表达式意外地引发了错误:错误   Domain = CNErrorDomain Code = 100“Access Denied”   UserInfo = {NSLocalizedDescription =拒绝访问,   NSLocalizedFailureReason =此申请尚未授予   访问联系人的权限。

我在苹果网站上找到了上面的代码,但我也在中间的隐私部分重新编写了这个代码:

  

对CNContactStore的任何调用都会在用户时阻止该应用程序   被要求授予或拒绝访问

但是没有出现要求访问联系人应用程序..我应该写更多代码来执行此操作吗?怎么样?

3 个答案:

答案 0 :(得分:1)

这是错的!使用do - catch语句,您就可以了。

do {
  try store.executeSaveRequest(saveRequest)
} catch {}

希望它有所帮助。

答案 1 :(得分:0)

也许您已阅读Contacts Framework Reference。你应该认为这样的整体描述在细节上很容易不准确。 Check the latest reference

CNContactStore有两种与授权相关的方法:

  

隐私权访问

     

+ authorizationStatusForEntityType:

     

- requestAccessForEntityType:completionHandler:

你应该在你的应用中写下这样的东西:

var store: CNContactStore!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    store = CNContactStore()
    checkContactsAccess()
}

private func checkContactsAccess() {
    switch CNContactStore.authorizationStatusForEntityType(.Contacts) {
    // Update our UI if the user has granted access to their Contacts
    case .Authorized:
        self.accessGrantedForContacts()

    // Prompt the user for access to Contacts if there is no definitive answer
    case .NotDetermined :
        self.requestContactsAccess()

    // Display a message if the user has denied or restricted access to Contacts
    case .Denied,
         .Restricted:
        let alert = UIAlertController(title: "Privacy Warning!",
                                      message: "Permission was not granted for Contacts.",
                                      preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

private func requestContactsAccess() {

    store.requestAccessForEntityType(.Contacts) {granted, error in
        if granted {
            dispatch_async(dispatch_get_main_queue()) {
                self.accessGrantedForContacts()
                return
            }
        }
    }
}

// This method is called when the user has granted access to their address book data.
private func accessGrantedForContacts() {
    //Update UI for grated state.
    //...
}

答案 2 :(得分:0)

这是swift的最新语法。希望对您有帮助!

           let store = CNContactStore()

            if CNContactStore.authorizationStatus(for: .contacts) == .notDetermined {
                store.requestAccess(for: .contacts) {granted, error in
                    if granted {
                        print("PERMISSION GRANTED")
                    } else {
                        print("PERMISSION NOT GRANTED")
                    }
                }
            } else if CNContactStore.authorizationStatus(for: .contacts) == .authorized {
                // If the user user has earlier provided the access, then add the contact
                print("AUTHORIZED")

                findContactsOnBackgroundThread { (contact) in
                    print("contacts : ",contact as Any)
                }
            } else {
                // If the user user has NOT earlier provided the access, create an alert to tell the user to go to Settings app and allow access
                print("NOT AUTHORIZED")
            }