Я пытаюсь сохранить контакт в приложении контактов, используя этот код напрямую, не запрашивая разрешения:
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
Ошибка :
фатальная ошибка: "попробуйте!" выражение неожиданно вызвало ошибку: Error Domain = CNErrorDomain Code = 100 «Доступ запрещен» UserInfo = {NSLocalizedDescription = Access Denied, NSLocalizedFailureReason = Этому приложению не предоставлено разрешение на доступ к контактам.
Я нашел приведенный выше код на веб-сайте Apple, но также выделил его в разделе «Конфиденциальность» посередине:
Любой вызов CNContactStore заблокирует приложение, пока пользователя просят предоставить или запретить доступ.
Но ничего не появляется с запросом на доступ к приложению контактов ... я должен написать еще код для этого? Как ?