系统SDK介绍-01

镇楼专用
  1. 访问联系人,并选择信息
  2. 拨号
  3. 发送短信
  4. 发送邮件
  5. 本地通知

接口文件

#import <Foundation/Foundation.h>
#import <ContactsUI/ContactsUI.h>

NS_ASSUME_NONNULL_BEGIN

@interface LZSystemSDKManager : NSObject

+ (instancetype)manager;

/**
 选择联系人  先添加权限

 @param result 选择的信息
 */
- (void)lz_selecteContactResulet:(void(^)(CNContact *obj))result API_AVAILABLE(ios(9.0));

/**
 发送邮件

 @param toRecipients 收件人群组
 @param ccRecipients 抄送人群组
 @param bccRecipients 密送人群组
 @param theme 主题
 @param emailContent 正文内容
 @param isHTML 是否是HTML格式
 @param result 发送结果
 */
- (void)lz_postEmialWithToRecipients:(NSArray<NSString *> *)toRecipients
                        ccRecipients:(NSArray<NSString *> *)ccRecipients
                       bccRecipients:(NSArray<NSString *> *)bccRecipients
                               theme:(NSString *)theme
                        emailContent:(NSString *)emailContent
                              isHTML:(BOOL)isHTML
                               reslt:(void(^)(NSInteger))result;
/**
 发送短信

 @param toRecipients 收件人群组
 @param content 内容
 @param result 发送结果
 */
- (void)lz_sendMessageWithToRecipients:(NSArray<NSString *> *)toRecipients
                               content:(NSString *)content
                               reslt:(void(^)(NSInteger))result;
/**
 拨号

 @param phoneNum 号码
 */
- (void)lz_dailPhone:(NSString *)phoneNum;

/**
 开启定位服务

 @param localResult 定位获取信息
 */
- (void)lz_openLocationService:(void(^)(id info))localResult;

/**
 IOS 10的通知   推送消息 支持的音频  图片 <= 10M  视频 <= 50M 
 
 @param body 消息内容
 @param promptTone 提示音
 @param soundName 音频
 @param imageName 图片
 @param movieName 视频
 @param identifier 消息标识
 */
-(void)lz_pushNotification_IOS_10_Title:(NSString *)title
                               subtitle:(NSString *)subtitle
                                   body:(NSString *)body
                             promptTone:(NSString *)promptTone
                              soundName:(NSString *)soundName
                              imageName:(NSString *)imageName
                              movieName:(NSString *)movieName
                           timeInterval:(NSTimeInterval)TimeInterval
                                repeats:(BOOL)repeats
                             Identifier:(NSString *)identifier API_AVAILABLE(ios(10.0));

/**
 IOS 10前的通知

 @param timeInterval 延迟时间
 @param repeatInterval 重复提醒次数
 @param alertBody 内容
 @param alertTitle 标题
 @param alertAction 滑动文字
 @param alertLaunchImage alertLaunchImage
 @param soundName 声音 为空则为系统声音
 @param userInfo 字典参数
 */
- (void)lz_pushNotifationWithTimeInterval:(NSTimeInterval)timeInterval
                           repeatInterval:(NSInteger)repeatInterval
                                alertBody:(NSString *)alertBody
                               alertTitle:(NSString *)alertTitle
                              alertAction:(NSString *)alertAction
                         alertLaunchImage:(NSString *)alertLaunchImage
                                soundName:(NSString *)soundName
                                 userInfo:(NSDictionary *)userInfo;
@end

NS_ASSUME_NONNULL_END

实现文件

#import "LZSystemSDKManager.h"
#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
#import <CoreLocation/CoreLocation.h>
#import <UserNotifications/UserNotifications.h>


#define kRootViewController  UIApplication.sharedApplication.delegate.window.rootViewController

@interface LZSystemSDKManager () <  CNContactPickerDelegate,
                                    MFMailComposeViewControllerDelegate,
                                    MFMessageComposeViewControllerDelegate,
                                    CLLocationManagerDelegate>

@property (nonatomic, copy) void (^selectContactResult)(CNContact *obj) API_AVAILABLE(ios(9.0));
@property (nonatomic, copy) void (^postEmailResult)(NSInteger obj);
@property (nonatomic, copy) void (^sendMessageResult)(NSInteger obj);
@property (nonatomic, copy) void (^locakResult)(id info);
@end

@implementation LZSystemSDKManager

+ (instancetype)manager {
    static dispatch_once_t onceToken;
    static LZSystemSDKManager *manager;
    dispatch_once(&onceToken, ^{
        manager = [[LZSystemSDKManager alloc] init];
    });
    return manager;
}

#pragma mark - 选择联系人信息
- (void)lz_selecteContactResulet:(void(^)(CNContact *obj))result API_AVAILABLE(ios(9.0)) {
    self.selectContactResult = result;

    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (status == CNAuthorizationStatusNotDetermined) {
        CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (error) {
                [self showHUDTitle:@"未获取访问权限" info:@"请前往设置中打开访问权限"];
            } else {
                CNContactPickerViewController * picker = [CNContactPickerViewController new];
                picker.delegate = self;
                picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
                [kRootViewController presentViewController: picker  animated:YES completion:nil];
            }
        }];
    }
    
    if (status == CNAuthorizationStatusAuthorized) {
        CNContactPickerViewController * picker = [CNContactPickerViewController new];
        picker.delegate = self;
        picker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
        [kRootViewController presentViewController: picker  animated:YES completion:nil];
    }
    else{
        [self showHUDTitle:@"未获取访问权限" info:@"请前往设置中打开访问权限"];
    }
}

#pragma mark - CNContactPickerDelegate
-  (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty API_AVAILABLE(ios(9.0)) {
    CNContact *contact = contactProperty.contact;
    self.selectContactResult(contact);
}

#pragma mark - 发送邮件
- (void)lz_postEmialWithToRecipients:(NSArray<NSString *> *)toRecipients
                        ccRecipients:(NSArray<NSString *> *)ccRecipients
                       bccRecipients:(NSArray<NSString *> *)bccRecipients
                               theme:(NSString *)theme
                        emailContent:(NSString *)emailContent
                              isHTML:(BOOL)isHTML
                               reslt:(nonnull void (^)(NSInteger))result {
    
    self.postEmailResult = result;
    MFMailComposeViewController *mailCompose = [[MFMailComposeViewController alloc] init];
    mailCompose.mailComposeDelegate = self;
    [mailCompose setToRecipients:toRecipients];
    [mailCompose setCcRecipients:ccRecipients];
    [mailCompose setBccRecipients:bccRecipients];
    [mailCompose setSubject:theme];
    [mailCompose setMessageBody:emailContent isHTML:isHTML];
    [kRootViewController presentViewController:mailCompose animated:YES completion:nil];
}

#pragma mark - MFMailComposeViewControllerDelegate的代理方法:
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    [controller dismissViewControllerAnimated:YES completion:nil];
     self.postEmailResult(result);
}


#pragma mark - 发送短信
- (void)lz_sendMessageWithToRecipients:(NSArray<NSString *> *)toRecipients content:(NSString *)content reslt:(nonnull void (^)(NSInteger))result {
    self.sendMessageResult = result;
        MFMessageComposeViewController *messageVC = [[MFMessageComposeViewController alloc] init];
    messageVC.recipients = toRecipients;
    messageVC.body = content;
    messageVC.messageComposeDelegate = self;
    [kRootViewController presentViewController:messageVC animated:YES completion:nil];
}

#pragma mark - MFMessageComposeViewControllerDelegate
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    [controller dismissViewControllerAnimated:true completion:nil];
    self.sendMessageResult(result);
}

#pragma mark - 拨号
- (void)lz_dailPhone:(NSString *)phoneNum {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phoneNum]]];
}

#pragma mark - 定位服务
- (void)lz_openLocationService:(void(^)(id info))localResult {
    self.locakResult = localResult;
    CLLocationManager *localManager = [[CLLocationManager alloc] init];
    localManager.delegate = self;
    localManager.desiredAccuracy = kCLLocationAccuracyBest;
    localManager.distanceFilter = kCLLocationAccuracyNearestTenMeters;
    [localManager requestWhenInUseAuthorization];
    
    if ([CLLocationManager locationServicesEnabled] ||
        [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse ||
        [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways) {
        
        [localManager startUpdatingLocation];
    } else {
        [self showHUDTitle:@"未获取定位权限" info:@"请前往设置中打开定位权限"];
    }
}

#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    CLLocation *currLocation = [locations lastObject];
    CLLocation *infLocation = [[CLLocation alloc] initWithLatitude:currLocation.coordinate.latitude longitude:currLocation.coordinate.longitude];
    
    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    
    [geocoder reverseGeocodeLocation:infLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error !=nil || placemarks.count == 0) {
            NSLog(@"%@",error);
            self.locakResult(nil);
            return ;
        }
        
        NSDictionary *infoDic = @{@"country":placemarks.firstObject.country,
                                  @"administrativeArea":placemarks.firstObject.administrativeArea,
                                  @"locality":placemarks.firstObject.locality,
                                  @"subLocality":placemarks.firstObject.subLocality,
                                  @"thoroughfare":placemarks.firstObject.thoroughfare,
                                  @"name":placemarks.firstObject.name
                                  };
        self.locakResult(infoDic);
    }];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [self showHUDTitle:@"未获取定位权限" info:@"请前往设置中打开定位权限"];
}

#pragma mark - 提示框
- (void)showHUDTitle:(NSString *)title info:(NSString *)info {
    
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:title message:info
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancal = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
            } else {
                
            }
        }
    }];
    
    [alterController addAction:cancal];
    [alterController addAction:sure];
    
    [kRootViewController presentViewController:alterController animated:true completion:nil];
}

#pragma mark - IOS 10前的通知
- (void)lz_pushNotifationWithTimeInterval:(NSTimeInterval)timeInterval
                           repeatInterval:(NSInteger)repeatInterval
                                alertBody:(NSString *)alertBody
                               alertTitle:(NSString *)alertTitle
                              alertAction:(NSString *)alertAction
                         alertLaunchImage:(NSString *)alertLaunchImage
                                soundName:(NSString *)soundName
                                 userInfo:(NSDictionary *)userInfo {
    // 定义本地通知对象
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 设置调用时间
    notification.timeZone = [NSTimeZone localTimeZone];
    //通知触发的时间,10s以后
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:timeInterval];
    // 通知重复次数
    notification.repeatInterval = repeatInterval;
    // 当前日历,使用前最好设置时区等信息以便能够自动同步时间
    notification.repeatCalendar = [NSCalendar currentCalendar];
    
    //设置通知属性
    // 通知主体
    notification.alertBody = alertBody;
    if (@available(iOS 8.2, *)) {
        notification.alertTitle = alertTitle;
    } else {
        // Fallback on earlier versions
    }
    // 应用程序图标右上角显示的消息数
    notification.applicationIconBadgeNumber += 1;
    // 待机界面的滑动动作提示
    notification.alertAction = alertAction;
    // 通过点击通知打开应用时的启动图片,这里使用程序启动图片
    notification.alertLaunchImage = alertLaunchImage;
    // 收到通知时播放的声音,默认消息声音
    notification.soundName = soundName.length == 0 ? UILocalNotificationDefaultSoundName : soundName;
    
    //设置用户信息
    notification.userInfo = userInfo;
    
    //调用通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

#pragma mark - IOS 10的通知
-(void)lz_pushNotification_IOS_10_Title:(NSString *)title
                               subtitle:(NSString *)subtitle
                                   body:(NSString *)body
                             promptTone:(NSString *)promptTone
                              soundName:(NSString *)soundName
                              imageName:(NSString *)imageName
                              movieName:(NSString *)movieName
                           timeInterval:(NSTimeInterval)TimeInterval
                                repeats:(BOOL)repeats
                             Identifier:(NSString *)identifier API_AVAILABLE(ios(10.0)) {
    
    //获取通知中心用来激活新建的通知
    UNUserNotificationCenter * center  = [UNUserNotificationCenter currentNotificationCenter];
    UNMutableNotificationContent * content = [[UNMutableNotificationContent alloc] init];
    content.title = title;
    content.subtitle = subtitle;
    content.body = body;
    
    //通知的提示音
    if ([promptTone containsString:@"."]) {
        UNNotificationSound *sound = [UNNotificationSound soundNamed:promptTone];
        content.sound = sound;
    }
    
    __block UNNotificationAttachment *imageAtt;
    __block UNNotificationAttachment *movieAtt;
    __block UNNotificationAttachment *soundAtt;
    
    if ([imageName containsString:@"."]) {
        [self addNotificationAttachmentContent:content attachmentName:imageName options:nil withCompletion:^(NSError *error, UNNotificationAttachment *notificationAtt) {
            imageAtt = [notificationAtt copy];
        }];
    }
    
    if ([soundName containsString:@"."]) {
        [self addNotificationAttachmentContent:content attachmentName:soundName options:nil withCompletion:^(NSError *error, UNNotificationAttachment *notificationAtt) {
            soundAtt = [notificationAtt copy];
        }];
    }
    
    if ([movieName containsString:@"."]) {
        // 在这里截取视频的第10s为视频的缩略图 :UNNotificationAttachmentOptionsThumbnailTimeKey
        [self addNotificationAttachmentContent:content attachmentName:movieName options:@{@"UNNotificationAttachmentOptionsThumbnailTimeKey":@10} withCompletion:^(NSError *error, UNNotificationAttachment *notificationAtt) {
            movieAtt = [notificationAtt copy];
        }];
    }
    
    NSMutableArray * array = [NSMutableArray array];
    
    if (imageAtt) {
        [array addObject:imageAtt];
    }
    
    if (soundAtt) {
        [array addObject:soundAtt];
    }
    
    if (movieAtt) {
        [array addObject:movieAtt];
    }
    
    content.attachments = array;
    
    //添加通知下拉动作按钮
    NSMutableArray * actionMutableArray = [NSMutableArray array];
    UNNotificationAction * actionA = [UNNotificationAction actionWithIdentifier:@"identifierNeedUnlock" title:@"进入应用" options:UNNotificationActionOptionAuthenticationRequired];
    UNNotificationAction * actionB = [UNNotificationAction actionWithIdentifier:@"identifierRed" title:@"忽略" options:UNNotificationActionOptionDestructive];
    [actionMutableArray addObjectsFromArray:@[actionA,actionB]];
    
    if (actionMutableArray.count > 1) {
        UNNotificationCategory * category = [UNNotificationCategory categoryWithIdentifier:@"categoryNoOperationAction" actions:actionMutableArray intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
        [center setNotificationCategories:[NSSet setWithObjects:category, nil]];
        content.categoryIdentifier = @"categoryNoOperationAction";
    }
    
    // UNTimeIntervalNotificationTrigger   延时推送
    // UNCalendarNotificationTrigger       定时推送
    // UNLocationNotificationTrigger       位置变化推送
    BOOL repeat = (TimeInterval > 60 && repeats) ? true : false;
    UNTimeIntervalNotificationTrigger * tirgger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:TimeInterval repeats:repeat];
    
    //建立通知请求
    UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:tirgger];
    
    //将建立的通知请求添加到通知中心
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        NSLog(@"%@本地推送 :( 报错 %@",identifier, error);
    }];
}


/**
 增加通知附件
 
 @param content 通知内容
 @param attachmentName 附件名称
 @param options 相关选项
 @param completion 结果回调
 */
-(void)addNotificationAttachmentContent:(UNMutableNotificationContent *)content attachmentName:(NSString *)attachmentName  options:(NSDictionary *)options withCompletion:(void(^)(NSError * error , UNNotificationAttachment * notificationAtt))completion  API_AVAILABLE(ios(10.0)) {
    
    NSArray * arr = [attachmentName componentsSeparatedByString:@"."];
    
    NSError * error;
    
    NSString * path = [[NSBundle mainBundle]pathForResource:arr[0] ofType:arr[1]];
    
    UNNotificationAttachment * attachment = [UNNotificationAttachment attachmentWithIdentifier:[NSString stringWithFormat:@"notificationAtt_%@",arr[1]] URL:[NSURL fileURLWithPath:path] options:options error:&error];
    
    if (error) {
        NSLog(@"attachment error %@", error);
    }
    
    completion(error,attachment);
    content.launchImageName = attachmentName;
}
@end
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,869评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,716评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,223评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,047评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,089评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,839评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,516评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,410评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,920评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,052评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,179评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,868评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,522评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,070评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,186评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,487评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,162评论 2 356

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,673评论 18 139
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,260评论 11 349
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 10,993评论 6 13
  • 不知是遭了什么罪,本想偷听的我,被岳老师抓个正着。 看来最近命犯太岁,总是被人在后面一击致命。 本想溜之大吉的,可...
    猴山有香蕉阅读 186评论 0 0
  • 请你走得小心一点 每步轻一点 加一些爱 又叫做大慈大悲 因为你有权救苦救难 又可以一脚就踏碎世界 我跑得不够快 断...
    野乂阅读 261评论 1 3