我正在尝试添加一个图像上传功能到我的iOS应用程序。我有一个函数selectPicture(),当用户点击上传按钮时会调用该函数,然后弹出一个警报,允许用户在相机和库之间进行选择。
func selectPicture() {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
let alertController = UIAlertController(title: "Image Source", message: "Please choose your image source", preferredStyle: UIAlertControllerStyle.alert)
let camera_action = UIAlertAction(title: "Camera", style: UIAlertActionStyle.default) {
(_: UIAlertAction) -> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
print ("Camera Selected")
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = true
imagePicker.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(imagePicker, animated: true, completion: nil)
}
}
let photoLibrary_action = UIAlertAction(title: "Photo Library", style: UIAlertActionStyle.default) {
(_: UIAlertAction) -> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
print ("Photo Library Selected")
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = true
imagePicker.navigationBar.titleTextAttributes = self.navbarAttributes
imagePicker.navigationBar.tintColor = UIColor.white
imagePicker.navigationBar.isTranslucent = false
imagePicker.navigationBar.barTintColor = PING_ORANGE
imagePicker.navigationController?.title = "Pick Image"
imagePicker.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(imagePicker, animated: true, completion: nil)
}
}
let cancel_action = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default) {
(_: UIAlertAction) -> Void in
print ("Cancel Selected")
}
alertController.addAction(camera_action)
alertController.addAction(photoLibrary_action)
alertController.addAction(cancel_action)
self.present(alertController, animated: true, completion: nil)
}
到目前为止,一切都很正常,但是当我选择一个图像时,委托方法没有被调用。
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any], editingInfo: [AnyHashable: Any]!) {
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
print("Image Print")
print(image)
if image != nil {
print ("INSIDE IMAGE DID FINISH PICKING")
dismiss(animated: false) {
self.uploadProfileImage(image: image!)
}
} else {
dismiss(animated: false) {
}
}
}
我刚开始使用swift,所以我可能漏掉了一些东西。有人能帮我吗?
谢谢你。
3条答案
按热度按时间cpjpxq1n1#
您可能使用的是旧代码。您的method signature是错误的。它应该是:
z9zf31ra2#
您需要将
let imagePicker = UIImagePickerController()
移到函数的作用域之外,以防止它被释放pxy2qtax3#
我使用以下命令修复了此问题: