当我使用照片库时,由于使用相机的iPad问题,我的应用程序被iTunes拒绝了。出于某种原因,它在didFinishPickingMediaWithInfo方法中崩溃。它适用于iPhone,但我不确定为什么它在iPad上无效。
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if(picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary)
{
//Crashing here -> "fatal error: unexpectedly found nil while unwrapping an Optional value"
var selectedImage: UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
appraisalPic.backgroundColor = UIColor.blackColor();
appraisalPic.image = selectedImage
self.dismissViewControllerAnimated(true, completion: nil)
}
答案 0 :(得分:2)
使用下面给出的代码而不是上面的代码,它可能会帮助你。
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if(picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary)
{
let url: NSString = info[UIImagePickerControllerReferenceURL] as NSString
var imageName:String = url.lastPathComponent
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
if let dirPath = paths[0] as? String {
let readPath = dirPath.stringByAppendingPathComponent(imageName)
var pickedimage = UIImage(CGImage: UIImage(contentsOfFile: readPath)!.CGImage, scale: 1.0, orientation: .Up)
appraisalPic.backgroundColor = UIColor.blackColor();
appraisalPic.image = pickedimage
}
}
}
}
答案 1 :(得分:1)
发生崩溃是因为您强制在后续行中展开可选值:
var selectedImage: UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
尝试按如下方式重写代码:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage where picker.sourceType == .PhotoLibrary else {
return
}
appraisalPic.backgroundColor = UIColor.blackColor()
appraisalPic.image = selectedImage
self.dismissViewControllerAnimated(true, completion: nil)
}
顺便说一句:你是否正确设置了picker.sourceType
?
let picker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
// ...
picker.sourceType = .PhotoLibrary
// ...
}
另请阅读GitHub's Swift Style Guide,尤其是Avoid Using Force-Unwrapping of Optionals。
答案 2 :(得分:1)
在iPad上,您必须使用presentViewController
显示图像选择器这是我在iPhone和iPad上展示的Obj-c代码。
entryInsulinsArray.forEach(function(entry) {
var entryPair = entry.split(",");
var date = parseFloat(entryPair[0]);
var value = entryPair[1];
var data = {
x: moment(date).format("HH:mm"),
y: entryPair[1]
}
result.push(entryPair[1]);
});