iOS,非视图类方法

时间:2022-11-04 10:28:08

1.判断类的实例

2.获取当前最高层Window

3.获取当前app是否活跃

4.允许所有请求

5.判断设备是否越狱

6.移除字符串换行符和空格

7.iOS注释方法或属性废弃或不可用

8.本地通讯录操作

判断类的实例

isKindOfClass        //判断是否是这个类或者这个类的子类的实例

例:[mystring isKindOfClass:[NSString class]]

isMemberOfClass  //判断是否是这个类的实例

例:[mystring isMemberOfClass:[NSString class]]

获取当前最高层Window

//防止提示被键盘遮挡,直接展示到最高

UIWindow *win=[[UIApplication sharedApplication].windows objectAtIndex:([UIApplication sharedApplication].windows.count-1)];

[win makeToast:@"发送消息内容超长,请分条发送。" duration:2 position:@"middle"];

获取当前app是否活跃

//当前app是活跃的在前台

[UIApplication sharedApplication].applicationState == UIApplicationStateActive

//当前app在后台

[UIApplication sharedApplication].applicationState ==UIApplicationStateBackground

允许所有请求(加下面代码加到Appdelegate头部,整个app就允许所有请求)

@implementation NSURLRequest(DataController)

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host

{

return YES;

}

@end

判断设备是否越狱

//读取应用列表,看看有无权限获取;不越狱的机器没有这个权限来判定的

- (BOOL)isJailBreak

{

if ([[NSFileManager defaultManager] fileExistsAtPath:@"/User/Applications/" ]) {

NSLog(@"该设备已越狱");

NSArray *applist = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/User/Applications/"  error:nil];

NSLog(@"applist = %@", applist);

return YES;

}

NSLog(@"该设备未越狱");

return NO;

}

//判断cydia的URL scheme确认是否越狱

- (BOOL)isJailBreak

{

if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://"]]) {

NSLog(@"该设备已越狱");

return YES;

}

NSLog(@"该设备未越狱");

return NO;

}

移除字符串换行符和空格

// 移除字符串换行符和空格

-(NSString*)removeSpaceAndLine:(NSString*)content{

// Scanner

NSScanner *scanner = [[NSScanner alloc] initWithString:content];

[scanner setCharactersToBeSkipped:nil];

NSMutableString *result = [NSMutableString string];

NSString *temp;

NSCharacterSet *newLineAndWhitespaceCharacters = [ NSCharacterSet whitespaceAndNewlineCharacterSet];// 去除空格

// Scan

while (![scanner isAtEnd]) {

//得到非换行非空格的字符

temp = nil;

[scanner scanUpToCharactersFromSet:newLineAndWhitespaceCharacters intoString:&temp];

if (temp) [result appendString:temp];

// Replace with a space

if ([scanner scanCharactersFromSet:newLineAndWhitespaceCharacters intoString:NULL]) {

if (result.length > 0 && ![scanner isAtEnd]) // Dont append space to beginning or end of result

[result appendString:@""];

}

}

// Return

return [NSString stringWithFormat:@"%@",result];

}

iOS注释方法或属性废弃或不可用

废弃

-(void)oldFunction __attribute__((deprecated("使用新API")));

@property(nonatomic,strong) NSString *oldString __attribute__((deprecated("使用新属性")));

不可用

-(void)oldFunction __attribute__((unavailable("使用新API")));

@property(nonatomic,strong) NSString *oldString __attribute__((unavailable("使用新属性")));

系统宏废弃方法

NS_AVAILABLE_IOS(5_0),告诉我们这个方法可以在iOS5.0及以后的版本中使用。如果我们在比指定版本更老的版本中调用这个方法,就会引起崩溃。

NS_AVAILABLE(5.0,2.0),这里表示这个方法随Mac OS 5.0和iOS 2.0及以后的版本中使用

NS_DEPRECATED_IOS(2_0, 6_0,"使用新API"),这个宏中有两个版本号。前面一个表明了这个方法被引入时的iOS版本,后面一个表明它被废弃时的iOS版本。被废弃并不是指这个方法就不存在了,只是意味着我们应当开始考虑将相关代码迁移到新的API上去了。

NS_DEPRECATED(10_0, 10_6, 2_0, 4_0,"使用新api"),这里表示这个方法随Mac OS 10.0和iOS 2.0被引入,在Mac OS 10.6和iOS 4.0后被废弃。

本地通讯录操作

//

//  AddressBookModel.h

//  AdderssBookSystemDemo

//  本地通讯录实体类

//  Created by Vie on 16/6/4.

//  Copyright © 2016年 Vie. All rights reserved.

//

#import <Foundation/Foundation.h>

@interface AddressBookModel : NSObject

@property (nonatomic, strong) NSString *name;//姓名(firstname,中文名只传这个)

@property (nonatomic, strong) NSString *lastName;//姓氏(中文名无需理会)

@property (nonatomic, strong) NSString *jobTitle;//职务

@property (nonatomic, strong) NSString *departmentName;//部门

@property (nonatomic, strong) NSString *companyName;//公司

@property (nonatomic, strong) NSMutableArray *telArray;//电话号码数组

@property (nonatomic, strong) NSMutableArray *emailArray;//邮箱

@property (nonatomic, strong) NSString *birthday;//生日(yyyy-MM-dd)

@property (nonatomic, strong) NSData *imageHead;//地址薄头像数据

@property (nonatomic, strong) NSString *createDateStr;//创建记录的日期

@property (nonatomic, strong) NSString *strModificationDateStr;//记录的最后修改日期

//@property (nonatomic, strong) NSString *country;//国家

//@property (nonatomic, strong) NSString *province;//省

//@property (nonatomic, strong) NSString *city;//城市

@end

//

//  AddressBookModel.m

//  AdderssBookSystemDemo

//

//  Created by Vie on 16/6/4.

//  Copyright © 2016年 Vie. All rights reserved.

//

#import "AddressBookModel.h"

@implementation AddressBookModel

-(instancetype)init{

self=[super init];

if (self) {

_telArray=[[NSMutableArray alloc] init];

_emailArray=[[NSMutableArray alloc] init];

}

return self;

}

@end

//

//  ManageLocalAddressBook.h

//  AdderssBookSystemDemo

//  管理通讯录操作类

//  Created by Vie on 2016/12/29.

//  Copyright © 2016年 Vie. All rights reserved.

//

#import <Foundation/Foundation.h>

#import "AddressBookModel.h"

@interface ManageLocalAddressBook : NSObject

/**

单例

@return 返回ManageLocalAddressBook

*/

+(ManageLocalAddressBook *)shareInstance;

/**

添加一个联系人到通讯录

@param addressBookModel addressBookModel 联系人实体类

@param block 添加成功或者失败

*/

-(void)addContactToAddressBook:(AddressBookModel *)addressBookModel flag:(void(^)(BOOL flag))block;

/**

添加多个联系人到通讯录

@param modelArray 联系人实体类数组

@param block 添加成功或者失败

*/

-(void)addContactsToAddressBookByArray:(NSArray *)modelArray flag:(void(^)(BOOL flag))block;

/**

加载本地通讯录

@param block 返回所有通讯录联系人信息数组

*/

-(void)loadLocalAddressBook:(void(^)(NSArray *modelArray))block;

/**

根据姓名模糊查询联系人

@param name 联系人姓名

@param block 匹配上的联系人

*/

-(void)selectContactFromAddressBookByName:(NSString *)name array:(void(^)(NSArray *modelArray))block;

/**

根据名字前缀模糊删除匹配联系人

@param name 联系人姓名

@param block 操作结果

*/

-(void)removeContactFrmoAddressBookByName:(NSString *)name flag:(void(^)(BOOL flag))block;

@end

//

//  ManageLocalAddressBook.m

//  AdderssBookSystemDemo

//

//  Created by Vie on 2016/12/29.

//  Copyright © 2016年 Vie. All rights reserved.

//

#import "ManageLocalAddressBook.h"

//读取通讯录需要到头文件

#import <AddressBook/AddressBook.h>

#import "AddressBookModel.h"

@interface ManageLocalAddressBook ()

@end

@implementation ManageLocalAddressBook

#pragma mark Initialize

+(ManageLocalAddressBook *)shareInstance{

static dispatch_once_t once;

static id instance;

dispatch_once(&once, ^{

instance=[[self alloc] init];

});

return instance;

}

#pragma mark manageLocalAddressBook  no ui

/**

检测/请求通讯录访问权限

@param block 是否授权

*/

-(void)checkAndRequestAddressBook:(void(^)(BOOL isAuthorized))block{

if (ABAddressBookGetAuthorizationStatus()!=kABAuthorizationStatusAuthorized) {

//请求通讯录权限

ABAddressBookRef addressBook=  ABAddressBookCreateWithOptions(NULL, NULL);

ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {

if (error) {

NSLog(@"Error: %@", (__bridge NSError *)error);

block(NO);

}else if (granted){

block(YES);

}else{

NSLog(@"没有通讯录访问权限");

block(NO);

}

});

}else{

block(YES);

}

}

/**

添加一个联系人到通讯录

@param addressBookModel addressBookModel 联系人实体类

@param block 添加成功或者失败

*/

-(void)addContactToAddressBook:(AddressBookModel *)addressBookModel flag:(void(^)(BOOL flag))block{

[self checkAndRequestAddressBook:^(BOOL isAuthorized) {

if (isAuthorized) {

//创建对系统地址薄的引用

ABAddressBookRef addressBooks=ABAddressBookCreate();

//创建一个个人信息

ABRecordRef newPerson=ABPersonCreate();

CFErrorRef error=NULL;

//添加firstname

if (addressBookModel.name) {

ABRecordSetValue(newPerson, kABPersonFirstNameProperty, (__bridge CFTypeRef)addressBookModel.name, &error);

}

//添加lastname

if (addressBookModel.lastName) {

ABRecordSetValue(newPerson, kABPersonLastNameProperty, (__bridge CFTypeRef)addressBookModel.lastName, &error);

}

//添加职务

if (addressBookModel.jobTitle) {

ABRecordSetValue(newPerson, kABPersonJobTitleProperty, (__bridge CFTypeRef)addressBookModel.jobTitle,&error);

}

//添加部门

if (addressBookModel.departmentName) {

ABRecordSetValue(newPerson, kABPersonDepartmentProperty, (__bridge CFTypeRef)addressBookModel.departmentName,&error);

}

//添加公司

if (addressBookModel.companyName) {

ABRecordSetValue(newPerson, kABPersonOrganizationProperty, (__bridge CFTypeRef)addressBookModel.companyName,&error);

}

//添加生日

if (addressBookModel.birthday) {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat: @"yyyy-MM-dd"];

ABRecordSetValue(newPerson, kABPersonBirthdayProperty, (__bridge CFTypeRef)[dateFormatter dateFromString:addressBookModel.birthday],&error);

}

//添加手机号码

if (addressBookModel.telArray.count>0) {

ABMutableMultiValueRef multiPhone=ABMultiValueCreateMutable(kABMultiStringPropertyType);

//多个手机号码

for (NSString *telString in addressBookModel.telArray) {

ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFTypeRef)telString, kABPersonPhoneMainLabel, NULL);

}

ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone, &error);

CFRelease(multiPhone);

}

//添加邮箱

if (addressBookModel.emailArray.count>0) {

ABMutableMultiValueRef multiEmail=ABMultiValueCreateMutable(kABMultiStringPropertyType);

for (NSString *emailString in addressBookModel.emailArray) {

//多个工作邮箱

ABMultiValueAddValueAndLabel(multiEmail, (__bridge CFTypeRef)emailString, kABWorkLabel, NULL);

}

ABRecordSetValue(newPerson, kABPersonEmailProperty, multiEmail, &error);

CFRelease(multiEmail);

}

//添加头像

if (addressBookModel.imageHead) {

ABPersonSetImageData(newPerson, (__bridge CFDataRef) addressBookModel.imageHead , &error);

}

//将信息添加到通讯录引用中

ABAddressBookAddRecord(addressBooks, newPerson, &error);

//保存通讯录

ABAddressBookSave(addressBooks, &error);

if (newPerson) {CFRelease(newPerson);}

block(error?false:true);

}else{

block(NO);

}

}];

}

/**

添加多个联系人到通讯录

@param modelArray 联系人实体类数组

@return 添加成功或者失败

*/

-(void)addContactsToAddressBookByArray:(NSArray *)modelArray flag:(void(^)(BOOL flag))block{

[self checkAndRequestAddressBook:^(BOOL isAuthorized) {

if (isAuthorized) {

//创建对系统地址薄的引用

ABAddressBookRef addressBooks=ABAddressBookCreate();

CFErrorRef error=NULL;

if (modelArray.count>0) {

for (AddressBookModel *addressBookModel in modelArray) {

//创建一个个人信息

ABRecordRef newPerson=ABPersonCreate();

//添加firstname

if (addressBookModel.name) {

ABRecordSetValue(newPerson, kABPersonFirstNameProperty, (__bridge CFTypeRef)addressBookModel.name, &error);

}

//添加lastname

if (addressBookModel.lastName) {

ABRecordSetValue(newPerson, kABPersonLastNameProperty, (__bridge CFTypeRef)addressBookModel.lastName, &error);

}

//添加职务

if (addressBookModel.jobTitle) {

ABRecordSetValue(newPerson, kABPersonJobTitleProperty, (__bridge CFTypeRef)addressBookModel.jobTitle,&error);

}

//添加部门

if (addressBookModel.departmentName) {

ABRecordSetValue(newPerson, kABPersonDepartmentProperty, (__bridge CFTypeRef)addressBookModel.departmentName,&error);

}

//添加公司

if (addressBookModel.companyName) {

ABRecordSetValue(newPerson, kABPersonOrganizationProperty, (__bridge CFTypeRef)addressBookModel.companyName,&error);

}

//添加生日

if (addressBookModel.birthday) {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat: @"yyyy-MM-dd"];

ABRecordSetValue(newPerson, kABPersonBirthdayProperty, (__bridge CFTypeRef)[dateFormatter dateFromString:addressBookModel.birthday],&error);

}

//添加手机号码

if (addressBookModel.telArray.count>0) {

ABMutableMultiValueRef multiPhone=ABMultiValueCreateMutable(kABMultiStringPropertyType);

//多个手机号码

for (NSString *telString in addressBookModel.telArray) {

ABMultiValueAddValueAndLabel(multiPhone, (__bridge CFTypeRef)telString, kABPersonPhoneMainLabel, NULL);

}

ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone, &error);

CFRelease(multiPhone);

}

//添加邮箱

if (addressBookModel.emailArray.count>0) {

ABMutableMultiValueRef multiEmail=ABMultiValueCreateMutable(kABMultiStringPropertyType);

for (NSString *emailString in addressBookModel.emailArray) {

//多个工作邮箱

ABMultiValueAddValueAndLabel(multiEmail, (__bridge CFTypeRef)emailString, kABWorkLabel, NULL);

}

ABRecordSetValue(newPerson, kABPersonEmailProperty, multiEmail, &error);

CFRelease(multiEmail);

}

//添加头像

if (addressBookModel.imageHead) {

ABPersonSetImageData(newPerson, (__bridge CFDataRef) addressBookModel.imageHead , &error);

}

//将信息添加到通讯录引用中

ABAddressBookAddRecord(addressBooks, newPerson, &error);

if (newPerson) {CFRelease(newPerson);}

}

}

//保存通讯录

ABAddressBookSave(addressBooks, &error);

block(error?false:true);

}else{

block(nil);

}

}];

}

/**

加载本地通讯录

@param block 返回所有通讯录联系人信息数组

*/

-(void)loadLocalAddressBook:(void(^)(NSArray *modelArray))block{

[self checkAndRequestAddressBook:^(BOOL isAuthorized) {

if (isAuthorized) {

NSMutableArray *addressBookTemp=[[NSMutableArray alloc] init];

//新建一个通讯录类

ABAddressBookRef addressBooks = ABAddressBookCreate();

//获取通讯录中的所有人

CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBooks);

//通讯录中人数

CFIndex nPeople = ABAddressBookGetPersonCount(addressBooks);

//循环,获取每个人的个人信息

for (NSInteger i = 0; i < nPeople; i++)

{

//新建一个addressBook model类

AddressBookModel *addressBook = [[AddressBookModel alloc] init];

//获取个人

ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);

//获取个人名字

CFTypeRef abName = ABRecordCopyValue(person, kABPersonFirstNameProperty);

CFTypeRef abLastName = ABRecordCopyValue(person, kABPersonLastNameProperty);

CFStringRef abFullName = ABRecordCopyCompositeName(person);

NSString *nameString = (__bridge NSString *)abName;

NSString *lastNameString = (__bridge NSString *)abLastName;

if ((__bridge id)abFullName != nil) {

nameString = (__bridge NSString *)abFullName;

} else {

if ((__bridge id)abLastName != nil)

{

nameString = [NSString stringWithFormat:@"%@ %@", nameString, lastNameString];

}

}

addressBook.name = nameString;

//获取职务

CFTypeRef abJobTitle = ABRecordCopyValue(person, kABPersonJobTitleProperty);

addressBook.jobTitle=(__bridge NSString *)abJobTitle;

//获取部门

CFTypeRef abDepartmentName = ABRecordCopyValue(person, kABPersonDepartmentProperty);

addressBook.departmentName=(__bridge NSString *)abDepartmentName;

//获取公司

CFTypeRef abCompanyName = ABRecordCopyValue(person, kABPersonOrganizationProperty);

addressBook.companyName=(__bridge NSString *)abCompanyName;

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat: @"yyyy-MM-dd"];

//获取生日

CFTypeRef peopleBirthday=ABRecordCopyValue(person, kABPersonBirthdayProperty);

addressBook.birthday=[dateFormatter stringFromDate:(__bridge NSDate *)peopleBirthday];

//创建记录的日期

CFTypeRef peopleCreateDate=ABRecordCopyValue(person, kABPersonCreationDateProperty);

        addressBook.createDateStr=[dateFormatter stringFromDate:(__bridge NSDate *)peopleCreateDate];

//记录的最后修改日期

CFTypeRef peopleModificationDate=ABRecordCopyValue(person, kABPersonModificationDateProperty);

addressBook.strModificationDateStr=[dateFormatter stringFromDate:(__bridge NSDate *)peopleModificationDate];

//获取地址薄头像数据

CFDataRef imageData=ABPersonCopyImageData(person);

addressBook.imageHead=(__bridge NSData *) imageData;

//    addressBook.recordID = (int)ABRecordGetRecordID(person);

ABPropertyID multiProperties[] = {

kABPersonPhoneProperty,

kABPersonEmailProperty

};

NSInteger multiPropertiesTotal = sizeof(multiProperties) / sizeof(ABPropertyID);

for (NSInteger j = 0; j < multiPropertiesTotal; j++) {

ABPropertyID property = multiProperties[j];

ABMultiValueRef valuesRef = ABRecordCopyValue(person, property);

NSInteger valuesCount = 0;

if (valuesRef != nil) valuesCount = ABMultiValueGetCount(valuesRef);

if (valuesCount == 0) {

CFRelease(valuesRef);

continue;

}

//获取电话号码和email

for (NSInteger k = 0; k < valuesCount; k++) {

CFTypeRef value = ABMultiValueCopyValueAtIndex(valuesRef, k);

switch (j) {

case 0: {// Phone number

//使用数组处理多个手机号,并去掉 - 符号

[addressBook.telArray addObject:[(__bridge NSString*)value stringByReplacingOccurrencesOfString:@"-" withString:@""]];

break;

}

case 1: {// Email

[addressBook.emailArray addObject:(__bridge NSString*)value];

break;

}

}

CFRelease(value);

}

CFRelease(valuesRef);

}

//将个人信息添加到数组中,循环完成后addressBookTemp中包含所有联系人的信息

[addressBookTemp addObject:addressBook];

if (abName) {CFRelease(abName);}

if (abLastName){ CFRelease(abLastName);}

if (abFullName){ CFRelease(abFullName);}

if (abJobTitle) {CFRelease(abJobTitle);}

if (abDepartmentName) {CFRelease(abDepartmentName);}

if (abCompanyName) {CFRelease(abCompanyName);}

}

//如果本地没有通讯录也为nil

block((NSArray *)addressBookTemp) ;

}else{

block(nil);

}

}];

}

/**

根据姓名模糊查询联系人

@param name 联系人姓名

@param block 匹配上的联系人

*/

-(void)selectContactFromAddressBookByName:(NSString *)name array:(void(^)(NSArray *modelArray))block{

[self loadLocalAddressBook:^(NSArray *modelArray) {

NSPredicate *predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"name LIKE '*%@*'",name]];

   NSArray *matchingArray=[modelArray filteredArrayUsingPredicate:predicate];

block(matchingArray);

}];

}

/**

根据名字前缀模糊删除匹配联系人

@param name 联系人姓名

@param block 操作结果

*/

-(void)removeContactFrmoAddressBookByName:(NSString *)name flag:(void(^)(BOOL flag))block{

[self checkAndRequestAddressBook:^(BOOL isAuthorized) {

if (isAuthorized) {

ABAddressBookRef addressBooks=ABAddressBookCreate();

CFErrorRef error=NULL;

//名字前缀查询

CFArrayRef selectPeople=ABAddressBookCopyPeopleWithName(addressBooks, (__bridge CFStringRef)name);

for (int i; i<[(__bridge NSArray *)selectPeople count]; i++) {

//将信息从通讯录引用中移除

ABAddressBookRemoveRecord(addressBooks, CFArrayGetValueAtIndex(selectPeople,i), &error);

}

//保存通讯录

ABAddressBookSave(addressBooks, &error);

if (selectPeople) {CFRelease(selectPeople);}

block(error?false:true);

}else{

block(nil);

}

}];

}

@end