如何从联系人中获取联系人图片 URL?
Posted
技术标签:
【中文标题】如何从联系人中获取联系人图片 URL?【英文标题】:How to get the contact image URL from contacts? 【发布时间】:2013-12-26 11:49:03 【问题描述】:我需要从 AddressBook 中获取每个联系人的图片 url。我现在可以获取图像,但问题是我需要获取特定人的图像的资产 URL。目前我正在通过
获取联系人图片[UIImage imageWithData:(__bridge NSData *)ABPersonCopyImageData(person)]
请帮助我获取该特定图像的资产 URL。谢谢
【问题讨论】:
我不认为你可以获得资产URL,你可以读取图像并写入它。为什么需要 URL? @EsbenB 因为我需要将它保存到数据库,我认为将图像作为数据保存到数据库不是一个好主意。如果您建议任何其他方式,它将对我更有帮助。谢谢! 【参考方案1】:我认为您需要制作数据的本地副本,然后在数据库中保存对该本地副本的引用:
//create a fileName perhaps based on the contact name or a GUID
NSError *err;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);//find the cache dir. You might want to consider using the doc dir instead
NSString * path = [paths objectAtIndex:0];
path = [path stringByAppendingPathComponent:fileName];
[imgData writeToFile:path options:NSDataWritingAtomic error:&err];
if(!err)
///save path to the DB
【讨论】:
【参考方案2】:适用于 SWIFT 3 及更高版本的简单解决方案。
var users = [User]()
func getContact()
if #available(ios 9.0, *)
let contactStore = CNContactStore()
_ = [
CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactEmailAddressesKey]
// Get all the containers
var allContainers: [CNContainer] = []
do
allContainers = try contactStore.containers(matching: nil)
catch
print("Error fetching containers")
do
try contactStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor, CNContactImageDataKey as CNKeyDescriptor]))
(contact, cursor) -> Void in
if (!contact.emailAddresses.isEmpty)
//self.email.append(String(contact.emailAddresses))
for emailAdd:CNLabeledValue in contact.emailAddresses
let a = emailAdd.value
if a as String != ""
for (index, data) in self.users.enumerated()
if a as? String == data.email
print("Emial found in Contact",index,a as String)
if contact.isKeyAvailable(CNContactImageDataKey)
if let img = contact.imageData
self.users[index] = User( id: self.users[index].id, firstName: self.users[index].firstName, lastName: self.users[index].lastName, email: self.users[index].email, user_type: self.users[index].user_type,user_image: UIImage(data: img))
print("imag",img)
self.email.append(a as String)
catch
print("Handle the error please")
else
// Fallback
filteredData = email
dropDown.dataSource = filteredData
【讨论】:
以上是关于如何从联系人中获取联系人图片 URL?的主要内容,如果未能解决你的问题,请参考以下文章