1. 程式人生 > >iOS9中,Swift判斷相機,相簿許可權,選取圖片為頭像

iOS9中,Swift判斷相機,相簿許可權,選取圖片為頭像

在iOS7以後要開啟手機攝像頭或者相簿的話都需要許可權,在iOS9中更是更新了相簿相關api的呼叫

首先新建一個swift工程,在SB中放上一個按鈕,並在viewController中拖出點選事件

ok!按鈕和事件設定好以後,我們來引入要用到的庫,判斷攝像頭許可權,需要引入AVFoundation.framework,搜尋並進行新增

在ViewController中 import AVFoundation

並遵循以下幾個代理UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate

宣告我們需要的變數

    var img :UIImageView!
    var sheet:UIAlertController!

    var sourceType = UIImagePickerControllerSourceType.PhotoLibrary //將sourceType賦一個初值型別,防止呼叫時不賦值出現崩潰

viewDidLoad中:

override func viewDidLoad() {
        super.viewDidLoad()
        img = UIImageView(frame: CGRectMake(20, 120, 100, 100))
        self.view.addSubview(img)
       
    }

由於我們選擇相簿或者開啟攝像頭以後進行圖片編輯的操作是一樣的,所以我們將這段程式碼封裝到open方法裡面

//    開啟相簿或相機
    func open(){
        
        let imagePickerController:UIImagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.allowsEditing = true//true為拍照、選擇完進入圖片編輯模式
        imagePickerController.sourceType = sourceType
        self.presentViewController(imagePickerController, animated: true, completion:{
            
        })
 
  }

然後我們再將判斷相簿許可權和攝像頭許可權的程式碼封裝到各自的方法中進行呼叫

/**
     判斷相機許可權
     
     - returns: 有許可權返回true,沒許可權返回false
     */
    func cameraPermissions() -> Bool{
        
        let authStatus:AVAuthorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
        
        if(authStatus == AVAuthorizationStatus.Denied || authStatus == AVAuthorizationStatus.Restricted) {
            return false
        }else {
            return true
        }
        
    }
(相機許可權的判斷和OC基本一致,只是方法呼叫方法變化了而已)

    /**
     判斷相簿許可權
     
     - returns: 有許可權返回ture, 沒許可權返回false
     */
    
    func PhotoLibraryPermissions() -> Bool {
        
        let library:PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
        if(library == PHAuthorizationStatus.Denied || library == PHAuthorizationStatus.Restricted){
            return false
        }else {
            return true
        }
    }

(相簿許可權判斷這裡在iOS9之前都是用的AssetsLibrary庫,在iOS9之後引用的是Photos庫了,雖然依然可以呼叫AssetsLibrary庫進行判斷,但會有警告Photos庫的引用,import Photos就行

接下來就是在前面拖出的按鈕事件中進行程式碼編寫了:


@IBAction func picker(sender: AnyObject) {
        
        //判斷設定是否支援圖片庫和相機
        if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) && UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)){
        
            sheet = UIAlertController(title: nil, message: "選擇獲取頭像方式", preferredStyle: .ActionSheet)
        
            //取消
            let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: {(action) in
                print("取消")
            })
            sheet.addAction(cancelAction)
            
            
            //相簿
            let OKAction = UIAlertAction(title: "相簿", style: .Default, handler: {(action) in
                if(self.PhotoLibraryPermissions() == true){
                    self.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                    self.open()
                }else{
                    //彈出提示框
                    self.sheet = UIAlertController(title: nil, message: "請在設定中開啟相簿許可權", preferredStyle: .Alert)
                    
                    let tempAction = UIAlertAction(title: "確定", style: .Cancel) { (action) in
                        print("取消")
                        
                    }
                    self.sheet.addAction(tempAction)
                    self.presentViewController(self.sheet, animated: true, completion: nil)
                }
            })
            sheet.addAction(OKAction)
            
        
            //攝像頭
            let destroyAction = UIAlertAction(title: "攝像頭", style: .Default, handler: { (action) in
                if(self.cameraPermissions() == true){
                    self.sourceType = UIImagePickerControllerSourceType.Camera
                    self.open()
                }else {
                    //彈出提示框
                    self.sheet = UIAlertController(title: nil, message: "請在設定中開啟攝像頭許可權", preferredStyle: .Alert)

                    let tempAction = UIAlertAction(title: "確定", style: .Cancel) { (action) in
                    }
                    self.sheet.addAction(tempAction)
                    self.presentViewController(self.sheet, animated: true, completion: nil)
                }
            })
            sheet.addAction(destroyAction)
            
        }
        
            self.presentViewController(self.sheet, animated: true, completion: nil)
}


最後


//    取消圖片選擇操作
    func imagePickerControllerDidCancel(picker:UIImagePickerController)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
//    選擇完圖片操作
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
        img.image = image
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }

注:因前面判斷了相機判斷,demo只能在真機上執行

附上demo連結:點選開啟連結