从联系人 Swift 获取图像

Get image from Contact Swift

期望的行为

我想知道如何在 Swift

中最好地执行以下操作
  1. Display a contact picker window
  2. Allow a user to select a contact
  3. Fetch an image from that contact.

研究

在研究这个问题时,我确定,从 iOS 9 开始,Apple 引入了一个新框架 Contacts,用于访问联系人。我还了解到 Their documentation 描述了使用名为 Predicates 的系统从联系人获取信息。但是,我不确定如何实现这一点。

实施

Based primarly on this tutorial,我已经弄清楚如何显示联系人选取器 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?
}

}

提前致谢!!

根据 apple API reference doc 中的联系人图像相关的三个属性:

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.

您可以从 CNContactProperty 获取 CNContact 实例,然后在 CNContact class.

中访问 imageData

因此您的代码可能如下所示:

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
      ...
   }
}

在 SwiftUI 中,此结构创建圆形联系人图像。

创建结构;

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)
        }
    }
}

并在你的主体中调用它,并根据你的需要定义高度和宽度

 ContactImage(contact:contact,size:nil) 

和结果