打開攝像頭拍照更換圖片, 并保存到沙盒及本地相冊, 還有直接從圖庫選擇圖片以及一系列的權(quán)限判斷與跳轉(zhuǎn)

在vc中
先引入一個(gè)頭文件, 用于ios9下判斷是否有訪問系統(tǒng)相冊權(quán)限

#import <Photos/Photos.h>

先簽這倆協(xié)議

@interface NAMinePicModifyViewController ()< UIImagePickerControllerDelegate, UINavigationControllerDelegate>

寫個(gè)屬性

@property (nonatomic, strong) UIImagePickerController *imagePickerController;

寫個(gè)懶加載, 避免重復(fù)創(chuàng)建

- (UIImagePickerController *)imagePickerController{
    if (!_imagePickerController) {
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    
    //模態(tài)推出照相機(jī)頁面的樣式
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    }
return _imagePickerController;
}

在一個(gè)拍照觸發(fā)按鈕點(diǎn)擊事件, cell點(diǎn)擊事件也行,

#pragma mark - 選擇拍照
- (void)selectImageFromCamera{

    //判斷相機(jī)是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    
    //判斷是否開啟相機(jī)權(quán)限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    //權(quán)限未開啟
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"抱歉" message:@"您尚未開啟相機(jī)權(quán)限" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"去開啟" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
             NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            
            //info plist中URL type中添加一個(gè)URL Schemes添加一個(gè)prefs值
            if([[UIApplication sharedApplication] canOpenURL:url]){
                
                //跳轉(zhuǎn)到隱私
                 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=CAMERA"]];
                
            }
        }];
        
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"不了" style:UIAlertActionStyleDefault handler:nil];
        
        [alertController addAction:actionOK];
        [alertController addAction:actionCancel];
        
        
        [self presentViewController:alertController animated:YES completion:nil];

    }
    
    //權(quán)限已開啟
    else{

        self.imagePickerController.delegate = self;
        self.imagePickerController.allowsEditing = YES;
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self.imagePickerController animated:YES completion:^{}];
    }
}
//適用于沒有相機(jī)的設(shè)備
else{

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"抱歉" message:@"相機(jī)不可用" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];

    #pragma mark - 讓alert自動消失
     [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(creatAlert:) userInfo:alertController repeats:NO];

    }

}

#pragma mark - 讓警告消失
- (void)creatAlert:(NSTimer *)timer{

    UIAlertController *alert = [timer userInfo];
    [alert dismissViewControllerAnimated:YES completion:nil];
    alert = nil;

}


#pragma mark - ImagePicker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{

    [picker dismissViewControllerAnimated:YES completion:^{
    
    
    }];

    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    /* 此處info 有六個(gè)值
     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
     * UIImagePickerControllerOriginalImage;  // a UIImage 原始圖片
     * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后圖片
     * UIImagePickerControllerCropRect;       // an NSValue (CGRect)
     * UIImagePickerControllerMediaURL;       // an NSURL
     * UIImagePickerControllerReferenceURL    // an NSURL that references an asset in the AssetsLibrary framework
     * UIImagePickerControllerMediaMetadata    // an NSDictionary containing metadata from a captured photo
     */
    //保存圖片至本地
    [self saveImage:image withName:@"currentImage.png"];

    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"currentImage.png"];
    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];

//這個(gè)本來是想用于拍照后編輯的, 發(fā)現(xiàn)并沒有用
    //self.isFullScreen = NO;

    //用拍下來的照片賦值
    [_headerView.buttonOfIcon setImage:savedImage forState:UIControlStateNormal];


    //訪問相冊權(quán)限, ios9之后的api, 要引入<Photos/Photos.h>
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];

    //相冊權(quán)限已開啟
    if(status == PHAuthorizationStatusAuthorized){
    
        //存入本地相冊
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
}

//未開啟相冊權(quán)限
//PHAuthorizationStatusNotDetermined,
//PHAuthorizationStatusRestricted
//PHAuthorizationStatusDenied
    else{

        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"您尚未開啟相冊權(quán)限" message:@"無法存入所拍的照片" preferredStyle:UIAlertControllerStyleAlert];
    
        UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"去開啟" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        
        //info plist中URL type中添加一個(gè)URL Schemes添加一個(gè)prefs值
        if([[UIApplication sharedApplication] canOpenURL:url]){
            
            //跳轉(zhuǎn)到隱私
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=PHOTOS"]];
            
        }
    }];
    
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"不了" style:UIAlertActionStyleDefault handler:nil];
    
    [alertController addAction:actionOK];
    [alertController addAction:actionCancel];
    
    
    [self presentViewController:alertController animated:YES completion:nil];

}

}

#pragma mark - 存儲到系統(tǒng)相冊結(jié)果回調(diào)
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{

    if (error)
    {
        NSLog(@"%@", error);
    
    }
    else
    {
        NSLog(@"保存成功");
    }

}

#pragma mark - 保存圖片至沙盒
- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName{

    if (UIImagePNGRepresentation(currentImage)) {
    
   data = UIImagePNGRepresentation(currentImage);
    
}else{
    
   data = UIImageJPEGRepresentation(currentImage, 1.0);
    
}

    //獲取沙盒目錄
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];

    //將圖片寫入文件
    //atomically:這個(gè)參數(shù)意思是如果為YES則保證文件的寫入原子性,就是說會先創(chuàng)建一個(gè)臨時(shí)文件,直到文件內(nèi)容寫入成功再導(dǎo)入到目標(biāo)文件里.如果為NO,則直接寫入目標(biāo)文件里
    [data writeToFile:fullPath atomically:NO];

}

在視圖類中, 對每次程序啟動進(jìn)行判斷

#pragma mark - 確保每次運(yùn)行都是上次修改后的照片
//讀取圖片
NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"currentImage.png"];
UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];

//本地有的話直接讀取沙盒本地
if (savedImage) {
    [_buttonOfIcon setImage:savedImage forState:UIControlStateNormal];
}
//沒有的話是默認(rèn)初始圖片
else{
    [_buttonOfIcon setImage:[UIImage imageNamed:@"sendPhoto"] forState:UIControlStateNormal];
}

調(diào)用系統(tǒng)相冊、相機(jī)發(fā)現(xiàn)是英文的系統(tǒng)相簿界面后標(biāo)題顯示“photos”,但是手機(jī)語言已經(jīng)設(shè)置顯示中文,糾結(jié)半天,最終在info.plist設(shè)置解決問題

info.plist里面添加Localized resources can be mixed YES

表示是否允許應(yīng)用程序獲取框架庫內(nèi)語言。

最后 感謝http://my.oschina.net/joanfen/blog/134677

--------------------我是分割線----------------------------------
此處感謝http://www.xuanyusong.com/archives/1493
接下來說打開本地相冊選取圖片

pragma mark - 選擇打開本地圖庫

- (void)openLocalAlbum{

self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.imagePickerController.delegate = self;
//設(shè)置選擇后的圖片可被編輯
self.imagePickerController.allowsEditing = YES;
[self presentViewController:self.imagePickerController animated:YES completion:^{}];

}

再配合之前寫的

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info

方法即可, 如果已經(jīng)寫了, 則不用再寫一遍, 也不用分開判斷

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,725評論 25 709
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,030評論 4 61
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,502評論 19 139
  • 今天的讀書會主題是:從弗洛伊德這杯酒中品人格心理學(xué)。一個(gè)小時(shí)的學(xué)習(xí)與分享在愉快的閱讀體驗(yàn)中不知不覺地結(jié)束了。深?yuàn)W的...
    筱箖2017閱讀 307評論 0 0
  • 在上一篇文章中,Jason老師提到名詞從句在句子中可以做主語、賓語和補(bǔ)語。 今天,Jason老師繼續(xù)帶大家了解名詞...
    JasonEnglish閱讀 665評論 0 0

友情鏈接更多精彩內(nèi)容