iOS开发,常用手机功能的使用

iOS开发中经常会用到一些手机自带的功能,每次使用都要重新找觉得麻烦,这里就进行一个汇总,方便以后的使用。这里以保证功能的基本使用为目的,主要涉及有以下功能:

电话
短信
邮件
麦克风
听筒外放切换
监测耳机拔插状态
相机相册
摇一摇
地图及定位
通讯录
3D Touch
亮度调节
1.拨打电话

第一种方式,直接拨打电话不会出现弹框提示

NSURL *url = [NSURL URLWithString:@"tel://10010"];
[[UIApplication sharedApplication] openURL:url];

第二种方式,拨打电话前会弹框提示确认

NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://10010"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];

第三种方式,使用webView实现的拨打电话功能,会出现弹框提示

UIWebView *webView;
webView = [[UIWebView alloc] initWithFrame:CGRectZero];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"tel://10010"]]];
[self.view addSubview:webView];
2.发送短信

第一种方式,直接跳转短信编辑页面,需要在短信编辑页面编辑短信内容

NSURL *url = [NSURL URLWithString:@"sms://10010"];
[[UIApplication sharedApplication] openURL:url];

第二种方式,跳转短信编辑页面,提前设置好短信内容以及收信人,可以直接发送。需要引入MessageUI.frameWork 然后文件中导入 #import ,实现MFMessageComposeViewControllerDelegate中的方法

- (void)sendMessage {
   if ([MFMessageComposeViewController canSendText]) {
        MFMessageComposeViewController *messageVC = [[MFMessageComposeViewController alloc] init];
        messageVC.body = @"你好,这是一条测试短信";
        messageVC.recipients = @[@"10010", @"10086"];
        messageVC.messageComposeDelegate = self;
        [self presentViewController:messageVC animated:YES completion:nil];
    } else {
        NSLog(@"发送短信功能不可用");
    }
}
#pragma mark -- MFMessageComposeViewControllerDelegate

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:          (MessageComposeResult)result{
         [controller dismissModalViewControllerAnimated:NO];//关键的一句   不能为YES
        switch ( result ) {
         case MessageComposeResultCancelled:
                NSLog(@"取消发送");
                break;
            case MessageComposeResultFailed:// send failed
                NSLog(@"发送失败");
                break;
            case MessageComposeResultSent:
                NSLog(@"发送成功");
                break;
            default:
                break;
        }
}
3.发送邮件

第一种方式,直接跳转邮箱,手动编辑主题和内容,发送完留在邮箱不会返回应用程序

NSURL *url = [NSURL URLWithString:@"mailto:[email protected]"];
[[UIApplication sharedApplication] openURL:url];

第二种方式,跳转邮箱界面,提前编辑好邮件主题及内容,添加邮件的对象,可以直接发送。需要引入MessageUI.frameWork 然后文件中导入#import ,实现MFMailComposeViewControllerDelegate中的方法

- (void)sendMail {
    if (![MFMailComposeViewController canSendMail]) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"不能发送邮件" message:@"请检查邮箱设置" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *myAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:myAction];
         [self presentViewController:alertController animated:YES completion:nil];
            return;
     } else {
            MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
            mailVC.mailComposeDelegate = self;
            //设置收件人
            [mailVC setToRecipients:@[@"[email protected]"]];
            //    //添加抄送及密送
            //    NSArray *ccRecipients = [NSArray arrayWithObjects:@"[email protected]", @"[email protected]", nil];
            //    [mailVC setCcRecipients:ccRecipients];
            //    NSArray *bccRecipients = [NSArray arrayWithObjects:@"[email protected]", nil];
            //    [mailVC setBccRecipients:bccRecipients];
            //设置主题
            [mailVC setSubject:@"全体通知"];
            //添加邮件正文
            [mailVC setMessageBody:@"这里就是群发邮件的内容了" isHTML:NO];
            //添加照片
            UIImage *addPic = [UIImage imageNamed:@"beauty.jpg"];
            NSData *imageData = UIImagePNGRepresentation(addPic);
            [mailVC addAttachmentData:imageData mimeType:@"" fileName:@"icon_star_full.png"];
            //还可以添加pdf文件及视频
            [self presentViewController:mailVC animated:YES completion:nil];
        }
}
#pragma mark -- MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [controller dismissViewControllerAnimated:YES completion:nil];
    NSString *mailResult;
    switch (result)
    {
        case MFMailComposeResultCancelled:
            mailResult = @"用户取消编辑邮件";
            break;
        case MFMailComposeResultSaved:
            mailResult = @"用户成功保存邮件";
            break;
        case MFMailComposeResultSent:
            mailResult = @"用户点击发送,将邮件放到队列中,还没发送";
            break;
        case MFMailComposeResultFailed:
            mailResult = @"用户试图保存或者发送邮件失败";
            break;
        default:
            mailResult = @"";
            break;
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:mailResult message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *myAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:myAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
4.麦克风

需要先引入AVFoundation.framework框架,然后在使用页面中导入#import

- (void)useMyMic {
    AVAudioSession *avSession = [AVAudioSession sharedInstance];
    if ([avSession respondsToSelector:@selector(requestRecordPermission:)]) {
        [avSession requestRecordPermission:^(BOOL available) {
            if (available) {
                //completionHandler
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"麦克风无法使用" message:@"请在“设置-隐私-麦克风”选项中允许应用访问你的麦克风" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *myAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil];
                    [alertController addAction:myAction];
                    [self presentViewController:alertController animated:YES completion:nil];
                });
            }
        }];
    }
}
5.播放声音

自动监测和耳朵的距离切换听筒和外放模式,引入AVFoundation.framework框架,然后页面中导入#import

//播放音乐
- (void)playTheSound {
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //默认情况下外放播放
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    NSError *playerError;
    NSString *string = [[NSBundle mainBundle] pathForResource:@"安静" ofType:@"mp3"];
    //把音频文件转换成url格式
    NSURL *url = [NSURL fileURLWithPath:string];
    //初始化音频类 并且添加播放文件
    myPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    myPlayer.meteringEnabled = YES;
    myPlayer.delegate = self;
    if (myPlayer == nil)
    {
        NSLog(@"ERror creating player: %@", [playerError description]);
    }
    [self handleNotification:YES];
    [myPlayer play];
}
- (void) handleNotification:(BOOL)state
{
    [[UIDevice currentDevice] setProximityMonitoringEnabled:state]; //建议在播放之前设置yes,播放结束设置NO,这个功能是开启红外感应
    if(state)//添加监听
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(sensorStateChange:) name:@"UIDeviceProximityStateDidChangeNotification"
                                                   object:nil];
    else//移除监听
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIDeviceProximityStateDidChangeNotification" object:nil];
}
//处理监听触发事件
-(void)sensorStateChange:(NSNotificationCenter *)notification;
{
    //如果此时手机靠近面部放在耳朵旁,那么声音将通过听筒输出,并将屏幕变暗(省电啊)
    if ([[UIDevice currentDevice] proximityState] == YES) {
        NSLog(@"Device is close to user");
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    } else {
        NSLog(@"Device is not close to user");
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    }
}
#pragma mark -- AVAudioPlayerDelegate
//播放结束,移除监听
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    [self handleNotification:NO];
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
}
6.监测耳机状态
//监测耳机状态
- (void)checkHeadphone {
    [[AVAudioSession sharedInstance] setActive:YES error:nil];//创建单例对象并且使其设置为活跃状态.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:)   name:AVAudioSessionRouteChangeNotification object:nil];//设置通知
}
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification
{
    NSDictionary *interuptionDict = notification.userInfo;
    NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    switch (routeChangeReason) {
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
            tipWithMessage(@"耳机插入");
            break;
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
            NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
            tipWithMessage(@"耳机拔出,停止播放操作");
            break;
        case AVAudioSessionRouteChangeReasonCategoryChange:
            // called at start - also when other audio wants to play
            tipWithMessage(@"AVAudioSessionRouteChangeReasonCategoryChange");
            break;
    }
}
//自定提醒窗口
NS_INLINE void tipWithMessage(NSString *message){
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [alerView show];
        [alerView performSelector:@selector(dismissWithClickedButtonIndex:animated:) withObject:@[@0, @1] afterDelay:0.9];
    });
}
7.调用相机或者调取相册

使用UIImagePickerController,要遵守协议UINavigationControllerDelegate,UIImagePickerControllerDelegate

- (IBAction)pickImage:(UIButton *)sender {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"获取图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        //判断是否支持相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
                imagePickerController.delegate = self;
                imagePickerController.allowsEditing = YES;
                imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:imagePickerController animated:YES completion:nil];
            }];
            [alertController addAction:defaultAction];
        }
        UIAlertAction *anotherAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *imageController = [[UIImagePickerController alloc] init];
            imageController.delegate = self;
            imageController.allowsEditing = YES;
            imageController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imageController animated:YES completion:nil];
        }];
        [alertController addAction:anotherAction];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];
}
//保存图片到沙盒文件
- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName {
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 1);
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    [imageData writeToFile:fullPath atomically:YES];
}
#pragma mark — UIImagePickerControllerDelegate
//确定选中相片后调用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self saveImage:image withName:@"picker.png"];
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"picker.png"];
    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
    [_imageView setImage:savedImage];
}
//取消选中时调用
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}
8.摇一摇功能
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];
    [self becomeFirstResponder];
}
//下面的三个方法来对不同的状态进行处理
- (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    //检测到摇动
    self.view.backgroundColor = [UIColor redColor];
}
- (void) motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    //摇动取消
    self.view.backgroundColor = [UIColor greenColor];
}
- (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    //摇动结束
    if (event.subtype == UIEventSubtypeMotionShake) {
        //something happens
        self.view.backgroundColor = [UIColor whiteColor];
    }
}
9.系统的定位和地图的使用

使用定位功能,引入CoreLocation.framework,然后#import 遵守协议CLLocationManagerDelegate,在info.plist文件添加两个字段
NSLocationWhenInUseUsageDescription //允许在前台获取GPS的描述
NSLocationAlwaysUsageDescription //允许在前、后台获取GPS的描述
两个字段的值类型为布尔类型,全置为YES

//获取定位信息
- (void)getUserLocationInfo {
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.delegate = self;
        [_locationManager startUpdatingLocation];
    } else {
        [self presentViewController:[DEFINE alertViewWithMessage:@"定位功能不可用"] animated:YES completion:nil];
    }
}
#pragma mark -- CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
    //获取最后一个元素,作为当前位置
    CLLocation *location = locations.lastObject;
    CLLocationCoordinate2D coordinate = location.coordinate;
    CLLocationDirection direction = location.course;
    CLLocationSpeed speed = location.speed;
    
    _longitude = [NSString stringWithFormat:@"%f",coordinate.longitude];
    _latutude = [NSString stringWithFormat:@"%f",coordinate.latitude];
    _speed = [NSString stringWithFormat:@"%f",speed];
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate:date];
    //进行反地理编译
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    //进行反编译
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (placemarks.count) {
            for (CLPlacemark *placemark in placemarks) {
                NSLog(@"%@", placemark.name);
            }
        } else if (error == nil && placemarks.count == 0) {
            NSLog(@"没有获取到位置信息");
        } else if (error != nil) {
            NSLog(@"%@", error);
        }
    }];
    //停止定位
    [_locationManager stopUpdatingLocation];
}
- (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error {
    NSString *errorString;
    [manager stopUpdatingLocation];
    NSLog(@"Error: %@",[error localizedDescription]);
    switch([error code]) {
        case kCLErrorDenied:
            //Access denied by user
            errorString = @"请确保位置访问服务是可用的,可在设置-隐私进行设置";
            break;
        case kCLErrorLocationUnknown:
            //Probably temporary...
            errorString = @"获取用户位置信息出错";
            break;
        case kCLErrorNetwork:
            //Probably temporary...
            errorString = @"网络状况异常,请稍候重试";
            break;
        default:
            errorString = @"定位服务出错,请稍候重试";
            break;
    }
    [self presentViewController:[DEFINE alertViewWithMessage:errorString] animated:YES completion:nil];
}

使用地图,引入MapKit.framework,然后导入#import ,实现MKMapViewDelegate中的方法

//使用系统地图
-(void)initGUI{
    CGRect rect=[UIScreen mainScreen].bounds;
    _mapView=[[MKMapView alloc]initWithFrame:rect];
    [self.view addSubview:_mapView];
    //设置代理
    _mapView.delegate=self;
    //请求定位服务
    _locationManager=[[CLLocationManager alloc]init];
    if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
        [_locationManager requestWhenInUseAuthorization];
    }
    //用户位置追踪(用户位置追踪用于标记用户当前位置,此时会调用定位服务)
    _mapView.userTrackingMode=MKUserTrackingModeFollow;
    //设置地图类型
    _mapView.mapType=MKMapTypeStandard;
}
#pragma mark - MKMapViewDelegate
//更新用户位置,只要用户改变位置则调用此方法(包括第一次定位到用户位置)
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    NSLog(@"%@",userLocation);
    //设置地图显示范围(如果不进行区域设置会自动显示区域范围并指定当前用户位置为地图中心点)
    //    MKCoordinateSpan span=MKCoordinateSpanMake(0.01, 0.01);
    //    MKCoordinateRegion region=MKCoordinateRegionMake(userLocation.location.coordinate, span);
    //    [_mapView setRegion:region animated:true];
}
10.选择手机联系人

引入Contacts.frameworkContactsUI.framework, 然后#import #import 遵守CNContactPickerDelegate

//选择手机联系人
- (void)pickerConnectNum:(UIButton *)sender {
    CNContactPickerViewController *con = [[CNContactPickerViewController alloc] init];
    con.delegate = self;
    [self presentViewController:con animated:YES completion:nil];
}
#pragma mark -- CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    NSLog(@"%@", contact.phoneNumbers);
    NSString *phone = [NSString string];
    for (CNLabeledValue *value in contact.phoneNumbers) {
        if ([value.label isEqualToString:@"_$!!$_"]) {
            CNPhoneNumber *phoneNum = value.value;
            phone = phoneNum.stringValue;
        }
        if ([value.label isEqualToString:@"_$!!$_"]) {
            CNPhoneNumber *phoneNum = value.value;
            phone = phoneNum.stringValue;
        }
        if ([value.label isEqualToString:@"_$!!$_"]) {
            CNPhoneNumber *phoneNum = value.value;
            phone = phoneNum.stringValue;
        }
        if ([value.label isEqualToString:@"iPhone"]) {
            CNPhoneNumber *phoneNum = value.value;
            phone = phoneNum.stringValue;
        }
    }
    NSLog(@"%@", phone);
}
11.3D Touch功能的实现

主要分桌面快捷菜单和应用内的实现,桌面快捷菜单,重按应用图标弹出快捷菜单,在Appdelegate进行实现
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{}实现代码

    //快捷菜单的图标
    UIApplicationShortcutIcon *icon1=[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeCaptureVideo];
    UIApplicationShortcutIcon *icon2=[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeAdd];
    UIApplicationShortcutIcon *icon3=[UIApplicationShortcutIcon iconWithTemplateImageName:@"search"];
    //快捷菜单
    UIApplicationShortcutItem *item1=[[UIApplicationShortcutItem alloc]initWithType:@"1"
                                                                     localizedTitle:@"视频"
                                                                  localizedSubtitle:nil
                                                                               icon:icon1
                                                                           userInfo:nil];
    UIApplicationShortcutItem *item2=[[UIApplicationShortcutItem alloc]initWithType:@"1"
                                                                     localizedTitle:@"添加"
                                                                  localizedSubtitle:@"add ,you know"
                                                                               icon:icon2
                                                                           userInfo:nil];
    UIApplicationShortcutItem *item3=[[UIApplicationShortcutItem alloc]initWithType:@"1"
                                                                     localizedTitle:@"搜索"
                                                                  localizedSubtitle:nil
                                                                               icon:icon3
                                                                           userInfo:nil];
    //设置app的快捷菜单
    [[UIApplication sharedApplication] setShortcutItems:@[item1,item2,item3]];
//3D Touch按压程序图标的快捷项时触发的方法
-(void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
{
    NSString *title;
    if([shortcutItem.localizedTitle isEqualToString:@"视频"])
    {
        title=@"视频";
    }
    else if([shortcutItem.localizedTitle isEqualToString:@"添加"])
    {
        title=@"添加";
    }
    else if([shortcutItem.localizedTitle isEqualToString:@"搜索"])
    {
        title=@"搜索";
    }
    UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"提示"
                                                                          message:[NSString stringWithFormat:@"你点击了“%@”",title]
                                                                   preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action=[UIAlertAction actionWithTitle:@"知道了"
                                                  style:UIAlertActionStyleDefault
                                                handler:^(UIAlertAction *action) {
                                                    [alertController dismissViewControllerAnimated:YES completion:nil];
                                                }];
    [alertController addAction:action];
    [self.window.rootViewController presentViewController:alertController
                                                 animated:YES
                                               completion:nil];
}

应用内页面实现的3D Touch,遵守UIViewControllerPreviewingDelegate

//注册3D Touch
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    if([self is3DTouchAvailiable])
    {
        [self registerForPreviewingWithDelegate:self sourceView:self.view];
    }
}
//判断是否支持3D Touch
-(BOOL)is3DTouchAvailiable
{
    if(self.traitCollection.forceTouchCapability==UIForceTouchCapabilityAvailable)
        return YES;
    return NO;
}
#pragma mark -- UIViewControllerPreviewingDelegate
- (nullable UIViewController *)previewingContext:(id )previewingContext viewControllerForLocation:(CGPoint)location NS_AVAILABLE_IOS(9_0) {
    NSIndexPath *indexPath=[_tableView indexPathForRowAtPoint:CGPointMake(location.x, location.y-64)];
    if(indexPath)
    {
        MapViewController *detail=[[MapViewController alloc]init];
        //detail.preferredContentSize=CGSizeMake(300, 300);
        __weak typeof(self) wkSelf=self;
        //上拉时的出现的快捷菜单
        UIPreviewAction *topAction=[UIPreviewAction actionWithTitle:@"置顶" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * action, UIViewController * previewViewController) {
            [wkSelf.tableView reloadData];
        }];
        UIPreviewAction *deleteAction=[UIPreviewAction actionWithTitle:@"删除" style:UIPreviewActionStyleDestructive handler:^(UIPreviewAction *action, UIViewController * previewViewController) {
            [wkSelf.tableView reloadData];
        }];
        //传递上拉菜单项给detail
        detail.actions = @[topAction,deleteAction];
        return detail;
    }
    return nil;
}
- (void)previewingContext:(id )previewingContext commitViewController:(UIViewController *)viewControllerToCommit NS_AVAILABLE_IOS(9_0) {
    [self showViewController:viewControllerToCommit sender:self];
}
12.设置屏幕亮度
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _brightnessValue = [UIScreen mainScreen].brightness;
    //屏幕亮度值为0到1之间,1为亮度最高
    [[UIScreen mainScreen] setBrightness:1.0];
}
//离开本界面时亮度设置回进入界面时的亮度
- (void)viewWillDisappear:(BOOL)animated {
    [[UIScreen mainScreen] setBrightness:_brightnessValue];
}

你可能感兴趣的:(iOS开发,常用手机功能的使用)