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 <MessageUI/MessageUI.h>,實現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:example@qq.com"];
[[UIApplication sharedApplication] openURL:url];

第二種方式,跳轉郵箱界面,提前編輯好郵件主題及內容,添加郵件的對象,可以直接發送。需要引入MessageUI.frameWork 然后文件中導入#import <MessageUI/MessageUI.h>,實現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:@[@"example@qq.com"]];
            //    //添加抄送及密送
            //    NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
            //    [mailVC setCcRecipients:ccRecipients];
            //    NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", 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 <AVFoundation/AVFoundation.h>

- (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 <AVFoundation/AVFoundation.h>

//播放音樂
- (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<NSString *,id> *)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 <CoreLocation/CoreLocation.h>遵守協議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 <MapKit/MapKit.h>,實現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 <Contacts/Contacts.h> #import <ContactsUI/ContactsUI.h> 遵守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:@"_$!<Mobile>!$_"]) {
            CNPhoneNumber *phoneNum = value.value;
            phone = phoneNum.stringValue;
        }
        if ([value.label isEqualToString:@"_$!<Home>!$_"]) {
            CNPhoneNumber *phoneNum = value.value;
            phone = phoneNum.stringValue;
        }
        if ([value.label isEqualToString:@"_$!<Work>!$_"]) {
            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 <UIViewControllerPreviewing>)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 <UIViewControllerPreviewing>)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];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容