RAContactManager.m 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. //
  2. // RAContactManager.m
  3. // ContactDemo
  4. //
  5. // Created by Jack on 2018/12/24.
  6. // Copyright © 2018 USAI. All rights reserved.
  7. //
  8. #import "RAContactManager.h"
  9. #import <Contacts/Contacts.h>
  10. #import "CNContact+RAContact.h"
  11. @implementation RAContactManager
  12. + (instancetype)defaultManager {
  13. static RAContactManager *manager;
  14. static dispatch_once_t token;
  15. dispatch_once(&token, ^{
  16. manager = [[RAContactManager alloc] init];
  17. });
  18. return manager;
  19. }
  20. #pragma mark - Authorization
  21. - (void)requestAuthorization:(void(^)(BOOL granted))completion {
  22. if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized) {
  23. if (completion) {
  24. completion(YES);
  25. }
  26. } else {
  27. CNContactStore *store = [[CNContactStore alloc] init];
  28. [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
  29. if (completion) {
  30. completion(granted);
  31. }
  32. }];
  33. }
  34. }
  35. #pragma mark - Get
  36. - (void)searchContactWithPredicate:(NSPredicate *)predicate completionHandler:(void(^)(NSArray<CNContact *> *contacts, NSError *error))completion {
  37. // 创建联系人仓库
  38. CNContactStore *store = [[CNContactStore alloc] init];
  39. // 创建联系人的请求对象
  40. // keys决定能获取联系人哪些信息,例:姓名,电话,头像等
  41. NSArray *fetchKeys = @[
  42. CNContactIdentifierKey,
  43. CNContactGivenNameKey,
  44. CNContactFamilyNameKey,
  45. CNContactMiddleNameKey,
  46. CNContactImageDataKey,
  47. CNContactOrganizationNameKey,
  48. CNContactDepartmentNameKey,
  49. CNContactJobTitleKey,
  50. CNContactPhoneNumbersKey,
  51. CNContactEmailAddressesKey,
  52. CNContactPostalAddressesKey,
  53. CNContactSocialProfilesKey,
  54. CNContactUrlAddressesKey,
  55. CNContactNoteKey
  56. ];
  57. CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:fetchKeys];
  58. request.sortOrder = CNContactSortOrderFamilyName;
  59. request.predicate = predicate;
  60. // 请求联系人
  61. NSError *error = nil;
  62. NSMutableArray<CNContact *> *contacts = [NSMutableArray array];
  63. [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
  64. [contacts addObject:contact];
  65. }];
  66. if (error) {
  67. contacts = nil;
  68. }
  69. if (completion) {
  70. completion([contacts copy], error);
  71. }
  72. }
  73. - (void)fetchAllContactCompletionHandler:(void(^)(NSArray<CNContact *> *contacts, NSError *error))completion {
  74. [self searchContactWithPredicate:nil completionHandler:completion];
  75. }
  76. - (void)searchContactByKeyword:(NSString *)keyword completionHandler:(void(^)(NSArray<CNContact *> *contacts, NSError *error))completion {
  77. if (keyword) {
  78. [self searchContactWithPredicate:nil completionHandler:^(NSArray<CNContact *> *contacts, NSError *error) {
  79. if (error) {
  80. if (completion) {
  81. completion(nil, error);
  82. }
  83. } else {
  84. NSMutableArray<CNContact *> *keywordContacts = [NSMutableArray array];
  85. for (CNContact *c in contacts) {
  86. if ([c ra_containsKeyWord:keyword]) {
  87. [keywordContacts addObject:c];
  88. }
  89. }
  90. if (completion) {
  91. completion(keywordContacts, nil);
  92. }
  93. }
  94. }];
  95. } else {
  96. [self searchContactWithPredicate:nil completionHandler:completion];
  97. }
  98. }
  99. - (void)searchContactByName:(NSString *)name completionHandler:(void(^)(NSArray<CNContact *> *contacts, NSError *error))completion {
  100. [self searchContactWithPredicate:[CNContact predicateForContactsMatchingName:name] completionHandler:completion];
  101. }
  102. #pragma mark - Add
  103. - (void)insertContact:(CNMutableContact *)contact completionHandler:(void(^)(BOOL result,NSError *error))completion {
  104. if (contact) {
  105. CNContactStore *store = [[CNContactStore alloc] init];
  106. CNSaveRequest *request = [[CNSaveRequest alloc] init];
  107. [request addContact:contact toContainerWithIdentifier:nil];
  108. NSError *err;
  109. [store executeSaveRequest:request error:&err];
  110. if (completion) {
  111. completion(err == nil, err);
  112. }
  113. } else {
  114. if (completion) {
  115. completion(NO, [NSError errorWithDomain:NSCocoaErrorDomain code:404 userInfo:@{@"msg":@"contact is nil"}]);
  116. }
  117. }
  118. }
  119. #pragma mark - Remove
  120. - (void)removeContact:(CNContact *)contact completionHandler:(void(^)(BOOL result,NSError *error))completion {
  121. if (contact) {
  122. if (contact.identifier != nil) {
  123. CNContactStore *store = [[CNContactStore alloc] init];
  124. CNSaveRequest *request = [[CNSaveRequest alloc] init];
  125. [request deleteContact:contact.mutableCopy];
  126. NSError *err;
  127. [store executeSaveRequest:request error:&err];
  128. if (completion) {
  129. completion(err == nil, err);
  130. }
  131. } else {
  132. if (completion) {
  133. completion(NO, [NSError errorWithDomain:NSCocoaErrorDomain code:404 userInfo:@{@"msg":@"contact's identifier is nil"}]);
  134. }
  135. }
  136. } else {
  137. if (completion) {
  138. completion(NO, [NSError errorWithDomain:NSCocoaErrorDomain code:404 userInfo:@{@"msg":@"contact is nil"}]);
  139. }
  140. }
  141. }
  142. #pragma mark - Modify
  143. - (void)updateContact:(CNMutableContact *)contact completionHandler:(void(^)(BOOL result,NSError *error))completion {
  144. if (contact) {
  145. if (contact.identifier != nil) {
  146. CNContactStore *store = [[CNContactStore alloc] init];
  147. CNSaveRequest *request = [[CNSaveRequest alloc] init];
  148. [request updateContact:contact];
  149. NSError *err;
  150. [store executeSaveRequest:request error:&err];
  151. if (completion) {
  152. completion(err == nil, err);
  153. }
  154. } else {
  155. if (completion) {
  156. completion(NO, [NSError errorWithDomain:NSCocoaErrorDomain code:404 userInfo:@{@"msg":@"contact's identifier is nil"}]);
  157. }
  158. }
  159. } else {
  160. if (completion) {
  161. completion(NO, [NSError errorWithDomain:NSCocoaErrorDomain code:404 userInfo:@{@"msg":@"contact is nil"}]);
  162. }
  163. }
  164. }
  165. #pragma mark - Utils
  166. - (NSString *)getFirstLetterFromString:(NSString *)aString {
  167. if (aString) {
  168. NSMutableString *str = [NSMutableString stringWithString:aString];
  169. //带声调的拼音
  170. CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
  171. NSLog(@"%@",str);
  172. //不带声调的拼音
  173. CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
  174. //转化为大写拼音
  175. NSString *strPinYin = [str capitalizedString];
  176. NSString *firstString = [strPinYin substringToIndex:1];
  177. //判断姓名首位是否为大写字母
  178. NSString * regexA = @"^[A-Z]$";
  179. NSPredicate *predA = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexA];
  180. //获取并返回首字母
  181. return [predA evaluateWithObject:firstString] ? firstString : @"#";
  182. } else{
  183. return @"#";
  184. }
  185. }
  186. - (void)addContact:(CNContact *)contact toGroupDictionary:(NSMutableDictionary<NSString *, NSMutableArray<CNContact *> *> *)dic {
  187. if (contact && dic) {
  188. NSString *firstLetter = [self getFirstLetterFromString:contact.familyName];
  189. if (!dic[firstLetter]) {
  190. dic[firstLetter] = [NSMutableArray array];
  191. }
  192. [dic[firstLetter] addObject:contact];
  193. }
  194. }
  195. - (void)sortGroupedContactsByFamilyNameFirstLetter:(NSArray<CNContact *> *)contacts completion:(void(^)(NSArray<NSString *> *sortedKeys, NSDictionary<NSString *, NSArray<CNContact *> *> *contactGroup))completion {
  196. if (contacts && contacts.count > 0) {
  197. NSMutableDictionary<NSString *, NSMutableArray<CNContact *> *> *dic = [NSMutableDictionary dictionary];
  198. for (CNContact *c in contacts) {
  199. [self addContact:c toGroupDictionary:dic];
  200. }
  201. // 对Group排序
  202. [dic enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSMutableArray<CNContact *> * _Nonnull obj, BOOL * _Nonnull stop) {
  203. [obj sortUsingComparator:^NSComparisonResult(CNContact * _Nonnull obj1, CNContact * _Nonnull obj2) {
  204. return [obj1.familyName localizedCompare:obj2.familyName];
  205. }];
  206. }];
  207. NSArray *sortedKeys = [dic.allKeys sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
  208. return [obj1 localizedCompare:obj2];
  209. }];
  210. if (completion) {
  211. completion(sortedKeys, dic);
  212. }
  213. } else {
  214. if (completion) {
  215. completion(nil, nil);
  216. }
  217. }
  218. }
  219. @end