Skip to content

Instantly share code, notes, and snippets.

@1998code
Last active December 18, 2021 12:24
Show Gist options
  • Save 1998code/4f5568c377bd0a25c46181be944290a3 to your computer and use it in GitHub Desktop.
Save 1998code/4f5568c377bd0a25c46181be944290a3 to your computer and use it in GitHub Desktop.
SwiftUI 3 save contacts button
// iOS 15 or above
Button("+ Add to Contacts") {
// Create a mutable object to add to the contact.
// Mutable object means an object state that can be modified after created.
let contact = CNMutableContact()
// Name
contact.givenName = "Ming"
// Phone No.
contact.phoneNumbers = [CNLabeledValue(label: CNLabelPhoneNumberiPhone, value: CNPhoneNumber(stringValue: "12345678"))]
// Save the created contact.
let store = CNContactStore()
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
do {
try store.execute(saveRequest)
} catch {
print("Error occur: \(error)")
// Handle error
// may add a alert...
}
}
.buttonStyle(.borderedProminent)
.tint(.black)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment