1

I am trying to add a contact in device contact library through UITest file. I have added the privacy usage description in plist. But it still throws the following error :

This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's Info.plist must contain an NSContactsUsageDescription key with a string value explaining to the user how the app uses this data.

I am using following code to add the contact :

let newContact = CNMutableContact()
newContact.givenName = "XYZ"

newContact.phoneNumbers = [CNLabeledValue(
    label: CNLabelPhoneNumberiPhone,
    value: CNPhoneNumber(stringValue: "12345678"))]

newContact.organizationName = "abc"

// Saving contact
let saveRequest = CNSaveRequest()
let store = CNContactStore()
saveRequest.add(newContact, toContainerWithIdentifier:nil)
try! store.execute(saveRequest)

Same code successfully creates a contact when executed from development target.

AamirR
  • 11,672
  • 4
  • 59
  • 73
Vikas
  • 914
  • 7
  • 19
  • 1
    You don't have to access Contacts from tests. You should mock it. UPD: Contacts Frameworks is already well tested and your mission is to tests your app logic. – Andrew Mar 05 '18 at 10:40
  • @AndyC We are not testing Contacts Framework. But we need to add a contact for running our test case. – Vikas Mar 05 '18 at 10:43
  • Check this answer it should help you https://stackoverflow.com/a/22024428/1244597 – AamirR Mar 05 '18 at 10:44
  • @Vikas you should replace usage of concrete classes with protocols and then make mock in tests. Like `init(contactsService: ContactsServiceType)` and then create service that will conform to `ContactsServiceType` and implement required logic inside. This will allow you to hide implementation details (using of Contacts framework). Then in tests implement mock for ContactsServiceType and put this mock as parameter for your object initializer. So this is the way you can test your class without using real contacts framework. – Andrew Mar 05 '18 at 10:50
  • @AndyC Thanks for the help. I am little confused. Can you please give some example, that would save my life. – Vikas Mar 05 '18 at 11:10
  • @Vikas You can read more about DI and unit tests in this article: https://theiconic.tech/making-your-swift-code-more-testable-with-dependency-injection-and-protocols-b3cc0cc80173 – Andrew Mar 05 '18 at 11:24

0 Answers0