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

标签 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")
        }
    }



}

我在方法 saveContact 的最后一行 try store.executeSaveRequest(saveRequest) 出现错误

错误:

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=CNErrorDomain Code=100 "Access Denied" UserInfo={NSLocalizedDescription=Access Denied, NSLocalizedFailureReason=This application has not been granted permission to access Contacts.

我在 apple 网站上找到了上面的代码,但我也在中间的隐私部分标出了这个:

Any call to CNContactStore will block the application while the user is being asked to grant or deny access

但是没有任何内容要求访问联系人应用程序。我应该编写更多代码来执行此操作吗?怎么样?

最佳答案

错了!使用 do-catch 语句就可以了。

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

希望对您有所帮助。

关于ios - 如何将联系人保存到 iOS 中的联系人应用程序中 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39309823/

相关文章:

ios - 选择特定月份和年份的数据 sqlite xcode

iOS - 在应用程序崩溃前截取屏幕截图

xcode - 我应该在哪里放置代码来自定义 UISearchBar 中的取消按钮?

objective-c - 绘制三角形

iphone - 是否可以让您上传的 iPhone 应用程序自动更新?

iphone - 如何从 iOS 中已有的源代码创建静态库或框架

swift - 如何在 Swift 中更改 UIBarButtonItem 事件的功能

ios - CoreData 在第一次获取时无限期阻塞?

android - 如何将自定义字体系列应用于您的 flutter 应用程序?

iphone - 搜索 AB 地址簿 iOS SDK