Reputation: 7537
Desired Behavior
I am wondering how to best do the following in Swift
- Display a contact picker window
- Allow a user to select a contact
- Fetch an image from that contact.
Research
In researching this question, I have determined that, beginning in iOS 9, Apple introduced a new framework, Contacts
, for accessing contacts. I also learned that Their documentation describes using a system called Predicates
for fetching information from a contact. However, I am unsure of how to implement this.
Implementation
Based primarly on this tutorial, I have figured out how to present the Contacts Picker window.
import UIKit
import Contacts
import ContactsUI
class ViewController: UIViewController, CNContactPickerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func contactsPressed(_ sender: AnyObject) {
let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self;
self.present(contactPicker, animated: true, completion: nil)
}
func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) {
//Here is where I am stuck - how do I get the image from the contact?
}
}
Thanks in advance!!
Upvotes: 12
Views: 11252
Reputation: 5943
in SwiftUI this struct creates Rounded contact image.
create a struct;
struct ContactImage:View{
let contact:CNContact!
let size:CGFloat?
var body:some View{
if contact.imageData != nil {
Image(uiImage: UIImage(data: contact.imageData!)!)
.resizable()
.clipShape(Circle())
.padding(.all,2)
.overlay(Circle().stroke(Color.gray, lineWidth: 2))
.frame(width: size ?? 28, height: size ?? 28, alignment: .center)
}else{
Image(systemName: "person.fill")
.resizable()
.foregroundColor(Color(.darkGray))
.clipShape(Circle())
.padding(.all,2)
.overlay(Circle().stroke(Color.gray, lineWidth: 2))
.scaledToFit()
.frame(width: size ?? 28, height: size ?? 28, alignment: .center)
}
}
}
and call it in your main body and define height and width according to your need
ContactImage(contact:contact,size:nil)
and result
Upvotes: 0
Reputation: 4579
There are three properties related to contact images according to the API reference doc from apple:
Image Properties
var imageData: Data? The profile picture of a contact.
var thumbnailImageData: Data? The thumbnail version of the contact’s profile picture.
var imageDataAvailable: Bool Indicates whether a contact has a profile picture.
You can get the CNContact instance from CNContactProperty, and then access imageData
in CNContact class.
So your code may look like this:
func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) {
let contact = contactProperty.contact
if contact.imageDataAvailable {
// there is an image for this contact
let image = UIImage(data: contact.imageData)
// Do what ever you want with the contact image below
...
}
}
Upvotes: 23