UIActionsheet的定義和聲明我就不寫了,主要寫功能函數。
此功能函數是主要是從相冊中選取圖片還是直接調用照相機。
func actionSheet(actionSheet: IBActionSheet!, clickedButtonAtIndex buttonIndex: Int) {
var sourceType = UIImagePickerControllerSourceType.PhotoLibrary //默認是從相冊中選取圖片
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){ //判斷手機上的相機是否可用,不可用直接選擇默認的從相冊中選取圖片
if buttonIndex == 0{
sourceType = UIImagePickerControllerSourceType.PhotoLibrary //從相冊中選取圖片
//println("從相冊中選取")
}else{
sourceType = UIImagePickerControllerSourceType.Camera //調用相機
//println("拍照")
}
}
// 圖片選擇器的設置
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
imagePickerController.sourceType = sourceType
self.presentViewController(imagePickerController, animated: true, completion: nil)
}
//隱藏圖片選擇器
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
//圖片選擇器具體功能的實現
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var imageToSave:UIImage
imageToSave = info[UIImagePickerControllerEditedImage] as! UIImage //選擇的圖片
self.portraitImageView.image = imageToSave
var portraitData = UIImageJPEGRepresentation(imageToSave, 0.1) //圖片壓縮
//下面的代碼是指將圖片存儲到第三方平臺LeanCloud上,如果你不用這個可忽略,按自己的存儲即可
var imageFile = AVFile.fileWithName("head.png", data: portraitData) as! AVFile
imageFile.saveInBackgroundWithBlock({ (success:Bool, error:NSError!) -> Void in
if error == nil {
} else {
}
}, progressBlock: { (progress:Int) -> Void in
println(progress)
})
currentUser!.setObject(imageFile, forKey: "avatar")
currentUser!.saveInBackgroundWithBlock { (success:Bool, error:NSError!) -> Void in
if error == nil{
}else{
println("why can not")
}
}
//圖片選擇器隱藏
self.dismissViewControllerAnimated(true, completion: nil)
}