Uploading image to Firebase Storage - ios

I'm using this simple code to upload the image to firebase storage.
let imageName = UUID().uuidString
let storageRef = FIRStorage.storage().reference().child("Devices_Images").child("\(imageName).png")
// let metaData = FIRStorageMetadata()
// metaData.contentType = "image/png"
if let uploadData = UIImagePNGRepresentation(self.ImageView.image!) {
storageRef.put(uploadData, metadata: nil, completion: { (data, error) in
if error != nil {
print(error)
} else {
print("Image Uploaded Succesfully")
let profileImageUrl = data?.downloadURL()?.absoluteString
}
I keep getting this error:
[Generic] Creating an image format with an unknown type is an error
Actually the conversion and image type are all png! so why I keep getting this error!
The image is uploaded from alpum or camera as here:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let theInfo:NSDictionary = info as NSDictionary
let img:UIImage = theInfo.object(forKey: UIImagePickerControllerOriginalImage) as! UIImage
ImageView.image = img
self.dismiss(animated: true, completion: nil)
}
#IBAction func AddPictureBtnAction(_ sender: AnyObject) {
// addPictureBtnAtion.enabled = false
let alertController : UIAlertController = UIAlertController(title: "أضف جهازًا", message: "التقط صورة من الكاميرا أو اختر من الألبوم", preferredStyle: .actionSheet)
let cameraAction : UIAlertAction = UIAlertAction(title: "صورة من الكاميرا", style: .default, handler: {(cameraAction) in
print("camera Selected...")
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) == true {
self.imagePicker.sourceType = .camera
self.present()
}else{
self.present(self.showAlert("عذرًا", Message: "الكاميرا ليست متاحة في هذا الجهاز أو تم منع الوصول لها!"), animated: true, completion: nil)
}
})
let libraryAction : UIAlertAction = UIAlertAction(title: "صورة من الألبوم", style: .default, handler: {(libraryAction) in
print("Photo library selected....")
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) == true {
self.imagePicker.sourceType = .photoLibrary
self.present()
}else{
self.present(self.showAlert("عذرًا", Message: "ألبوم الصور ليس متاحًا في هذا الجهاز أو تم منع الوصول له!"), animated: true, completion: nil)
}
})
let cancelAction : UIAlertAction = UIAlertAction(title: "إلغاء", style: .cancel , handler: {(cancelActn) in
print("Cancel action was pressed")
})
alertController.addAction(cameraAction)
alertController.addAction(libraryAction)
alertController.addAction(cancelAction)
alertController.popoverPresentationController?.sourceView = view
alertController.popoverPresentationController?.sourceRect = view.frame
self.present(alertController, animated: true, completion: nil)
}
func present(){
self.present(imagePicker, animated: true, completion: nil)
}
/* func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
print("info of the pic reached :\(info) ")
self.imagePicker.dismissViewControllerAnimated(true, completion: nil)
} */
//Show Alert
func showAlert(_ Title : String!, Message : String!) -> UIAlertController {
let alertController : UIAlertController = UIAlertController(title: Title, message: Message, preferredStyle: .alert)
let okAction : UIAlertAction = UIAlertAction(title: "Ok", style: .default) { (alert) in
print("User pressed ok function")
}
alertController.addAction(okAction)
alertController.popoverPresentationController?.sourceView = view
alertController.popoverPresentationController?.sourceRect = view.frame
return alertController
}

Add "_" in your parameter in your imagePicker method.
func imagePickerController(_ picker: UIImagePickerController ...
Then to upload:-
//if let uploadData = UIImagePNGRepresentation(UIImage(cgImage: self.imageView.image! as! CGImage, scale: 1.0, orientation: .up)) as? NSData {
if let uploadData = UIImagePNGRepresentation(self.ImageView.image!) as? NSData {
storageRef.put(uploadData!, metadata: nil, completion: { (metadata, error) in
if error != nil {
print(error)
} else {
print("Image Uploaded Succesfully")
let profileImageUrl = data?.downloadURL()?.absoluteString
}
})
}

Related

There are two functions for uploading pictures in ViewController

I upload the image when button 1 is clicked, but the second image also shows the image uploaded by button 1!
What should I do so that the image uploaded on button 1 is displayed on image 1, and the image on the boat on button 2 is displayed on image 2?
Here is my code, thanks for your help
#IBAction func imageSelect(sender: Any){
let actionSheetController = UIAlertController()
let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { (alertAction) -> Void in
print("Tap 取消 Button")
}
let takingPicturesAction = UIAlertAction(title: "拍照", style: UIAlertAction.Style.destructive) { (alertAction) -> Void in
self.getImageGo(type: 1)
}
let photoAlbumAction = UIAlertAction(title: "相册", style: UIAlertAction.Style.default) { (alertAction) -> Void in
self.getImageGo(type: 2)
}
actionSheetController.addAction(cancelAction)
actionSheetController.addAction(takingPicturesAction)
actionSheetController.addAction(photoAlbumAction)
actionSheetController.popoverPresentationController?.sourceView = sender as? UIView
//显示
self.present(actionSheetController, animated: true, completion: nil)
}
#IBAction func imageSelect2(sender: Any){
let actionSheetController = UIAlertController()
let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { (alertAction) -> Void in
print("Tap 取消 Button")
}
let takingPicturesAction = UIAlertAction(title: "拍照", style: UIAlertAction.Style.destructive) { (alertAction) -> Void in
self.getImageGo(type: 1)
}
let photoAlbumAction = UIAlertAction(title: "相册", style: UIAlertAction.Style.default) { (alertAction) -> Void in
self.getImageGo(type: 2)
}
actionSheetController.addAction(cancelAction)
actionSheetController.addAction(takingPicturesAction)
actionSheetController.addAction(photoAlbumAction)
//iPad设备浮动层设置锚点
actionSheetController.popoverPresentationController?.sourceView = sender as? UIView
//显示
self.present(actionSheetController, animated: true, completion: nil)
}
func getImageGo(type:Int){
takingPicture = UIImagePickerController.init()
if(type==1){
takingPicture.sourceType = .camera
//takingPicture.showsCameraControls = true
}else if(type==2){
takingPicture.sourceType = .photoLibrary
}
takingPicture.allowsEditing = true
takingPicture.delegate = self
present(takingPicture, animated: true, completion: nil)
}
I think the problem is here in the code, but I don't know how to modify it, thanks for your help
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
takingPicture.dismiss(animated: true, completion: nil)
if(takingPicture.allowsEditing == false){
//原图
ID1.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
ID2.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
}else{
//截图
ID1.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
ID2.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
}
}

How to pick, display two images on two UIImageViews, and then upload these two chosen images to Firebase Database and Storage?

I want to pick two different images on two imageView's on one ViewController, display them, and after pushing the button save picked images to firebase database and storage to its particular user. My code only able to upload one picked image, not two different, I understand that the problem with UIImagePickerController part, but how can I resolve it. Full code of viewController is below. Please help!!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SettingProfileViewController.handleSelectProfileImageView(sender:)))
profilePhoto.addGestureRecognizer(tapGesture)
profilePhoto.isUserInteractionEnabled = true
let wallTapGesture = UITapGestureRecognizer(target: self, action: #selector(SettingProfileViewController.handleSelectWallpaperImageView(sender:)))
wallpaperPhoto.addGestureRecognizer(wallTapGesture)
wallpaperPhoto.isUserInteractionEnabled = true
profilePhoto.layer.cornerRadius = 60
profilePhoto.clipsToBounds = true
}
weak var activeImageView:UIImageView? = nil
#objc func handleSelectWallpaperImageView(sender: UIGestureRecognizer){
guard let sendingImageView = sender.view as? UIImageView else {
print("Ooops, received this gesture not from an ImageView")
return
}
activeImageView = sendingImageView
let actionSheet = UIAlertController(title: "New Photo", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Камера", style: .default, handler: { action in
self.showCamera()
}))
actionSheet.addAction(UIAlertAction(title: "Альбом ", style: .default, handler: {action in
self.showAlbum()
}))
actionSheet.addAction(UIAlertAction(title: "Отмена", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
#objc func handleSelectProfileImageView(sender: UIGestureRecognizer){
guard let sendingImageView = sender.view as? UIImageView else {
print("Ooops, received this gesture not from an ImageView")
return
}
activeImageView = sendingImageView
let actionSheet = UIAlertController(title: "New Photo", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Камера", style: .default, handler: { action in
self.showCamera()
}))
actionSheet.addAction(UIAlertAction(title: "Альбом ", style: .default, handler: {action in
self.showAlbum()
}))
actionSheet.addAction(UIAlertAction(title: "Отмена", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
func showCamera() {
let cameraPicker = UIImagePickerController()
cameraPicker.delegate = self
cameraPicker.sourceType = .camera
present(cameraPicker, animated: true, completion: nil)
}
func showAlbum(){
let cameraPicker = UIImagePickerController()
cameraPicker.delegate = self
cameraPicker.sourceType = .photoLibrary
present(cameraPicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true, completion: nil)
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
// selectedImage = image
activeImageView?.image = image
// currentImage = image
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
///для того чтобы загруженные фото, отображались на ProfileViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "profileVC" {
let destination = segue.destination as! ProfileViewController
destination.wImage = activeImageView?.image
}
}
#IBAction func saveTapped(_ sender: Any) {
let db = Firestore.firestore()
let did = Auth.auth().currentUser!.uid
let storageRef = Storage.storage().reference(forURL: "gs://crut-6c67c.appspot.com").child("profile_Image").child(did)
if let pImage = self.activeImageView?.image, let imageData = pImage.jpegData(compressionQuality: 0.1) {
storageRef.putData(imageData, metadata: nil, completion: {(metadata, Error) in
if Error != nil, metadata != nil {
return
}
storageRef.downloadURL { (url: URL?,error: Error?) in
if let profileImageUrl = url?.absoluteString{
db.collection("suppliers").document("ip").collection("ipinfo").document(did).setData(["Profile Image":profileImageUrl], merge: true)
}
}
})
}
let storyBoard: UIStoryboard = UIStoryboard(name: "Profile", bundle: nil)
let profileViewController = storyBoard.instantiateViewController(identifier:profile.Storyboard.profileViewController) as? ProfileViewController
self.view.window?.rootViewController = profileViewController
self.view.window?.makeKeyAndVisible()
}
}
You can make an instance variable in your viewController i.e.
private var isProfilePhotoSelecting = true
When user tap on profileImageView in handleSelectProfileImageView method set isProfilePhotoSelecting to true i.e.
#objc func handleSelectProfileImageView(sender: UIGestureRecognizer){
guard let sendingImageView = sender.view as? UIImageView else {
print("Ooops, received this gesture not from an ImageView")
return
}
// Updated the image under consideration
isProfilePhotoSelecting = true
let actionSheet = UIAlertController(title: "New Photo", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Камера", style: .default, handler: { action in
self.showCamera()
}))
actionSheet.addAction(UIAlertAction(title: "Альбом ", style: .default, handler: {action in
self.showAlbum()
}))
actionSheet.addAction(UIAlertAction(title: "Отмена", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
And on wallpaperImageView tapping in handleSelectWallpaperImageView method set isProfilePhotoSelecting to false i.e.
#objc func handleSelectWallpaperImageView(sender: UIGestureRecognizer){
guard let sendingImageView = sender.view as? UIImageView else {
print("Ooops, received this gesture not from an ImageView")
return
}
// Updated the image under consideration
isProfilePhotoSelecting = false
let actionSheet = UIAlertController(title: "New Photo", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Камера", style: .default, handler: { action in
self.showCamera()
}))
actionSheet.addAction(UIAlertAction(title: "Альбом ", style: .default, handler: {action in
self.showAlbum()
}))
actionSheet.addAction(UIAlertAction(title: "Отмена", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
Then update your imagePickerDelegate to :
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
if isProfilePhotoSelecting {
profilePhoto.image = image
} else {
wallpaperPhoto.image = image
}
}
dismiss(animated: true, completion: nil)
}
This will help you set both your images to their respective imageView. Then in saveTapped(_:) method you can check both imageViews for images and upload them i.e. Your saveTapped() method should look like this
#IBAction func saveTapped(_ sender: Any) {
let db = Firestore.firestore()
let did = Auth.auth().currentUser!.uid
let storageRef = Storage.storage().reference(forURL: "gs://crut-6c67c.appspot.com")
if let profileImage = self.profilePhoto.image, let imageData = profileImage.jpegData(compressionQuality: 0.1) {
let profileStorage = storageRef.child("profile_Image").child(did)
profileStorage.putData(imageData, metadata: nil, completion: {(metadata, Error) in
if Error != nil, metadata != nil {
return
}
profileStorage.downloadURL { (url: URL?,error: Error?) in
if let profileImageUrl = url?.absoluteString {
db.collection("suppliers").document("ip").collection("ipinfo").document(did).setData(["Profile Image":profileImageUrl], merge: true)
}
}
})
}
if let wallpaperImage = self.wallpaperPhoto.image, let imageData = wallpaperImage.jpegData(compressionQuality: 0.1) {
let wallpaperStorage = storageRef.child("wallpaper_Image").child(did)
wallpaperStorage.putData(imageData, metadata: nil, completion: {(metadata, Error) in
if Error != nil, metadata != nil {
return
}
wallpaperStorage.downloadURL { (url: URL?,error: Error?) in
if let wallpaperImageUrl = url?.absoluteString {
// Do your stuff with wallpaper image url here
}
}
})
}
let storyBoard: UIStoryboard = UIStoryboard(name: "Profile", bundle: nil)
let profileViewController = storyBoard.instantiateViewController(identifier:profile.Storyboard.profileViewController) as? ProfileViewController
self.view.window?.rootViewController = profileViewController
self.view.window?.makeKeyAndVisible()
}
Note: This will not wait for the images to upload as you are waiting for them to upload. But it depends on your usecase if you want to wait until the image uploading completes and then move to ProfileViewController, you can use DispatchGroup for that purpose.
I hope your saving the last choosen image on activeImageView and passing that to Firebase, hence only one image is getting uploaded.
Instead create and Array and both the images choosen from handleSelectWallpaperImageView and handleSelectWallpaperImageView, then loop through the Array and send to Firebase.
Check this for more information: https://stackoverflow.com/a/49934285/1244403
Created option Boolean variable
var isProfilePhotoSelecting:Bool?
#objc func handleSelectWallpaperImageView(sender: UIGestureRecognizer){
isProfilePhotoSelecting = false
///
other code
}
#objc func handleSelectProfileImageView(sender: UIGestureRecognizer){
isProfilePhotoSelecting = true
///
other code
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true, completion: nil)
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
if isProfilePhotoSelecting == true {
profilePhoto.image = image
}else {
wallpaperPhoto.image = image
}
}
}
In the saveTapped need to be added storage references to each chosen image and its respective database.
#IBAction func saveTapped(_ sender: Any) {
let db = Firestore.firestore()
let did = Auth.auth().currentUser!.uid
let storageRef = Storage.storage().reference(forURL: "gs://crut-6c67c.appspot.com").child("profile_Image").child(did)
if let profileImage = self.profilePhoto.image, let imageData = profileImage.jpegData(compressionQuality: 0.1){
storageRef.putData(imageData, metadata: nil, completion: {(metadata, Error) in
if Error != nil, metadata != nil {
return
}
storageRef.downloadURL { (url: URL?, error: Error?) in
if let profileImageUrl = url?.absoluteString {
db.collection("suppliers").document("ip").collection("ipinfo").document(did).setData(["Profile Image":profileImageUrl], merge: true)
}
}
})
}
let wallStoreRef = Storage.storage().reference(forURL: "gs://crut-6c67c.appspot.com").child("Wallpaper_Image").child(did)
if let wallpaperImage = self.wallpaperPhoto.image, let imageData = wallpaperImage.jpegData(compressionQuality: 0.1) {
wallStoreRef.putData(imageData, metadata: nil, completion: {(metadata, Error) in
if Error != nil, metadata != nil {
return
}
wallStoreRef.downloadURL { (url: URL?,error: Error?) in
if let wallpaperImageUrl = url?.absoluteString {
// Do your stuff with wallpaper image url here
db.collection("suppliers").document("ip").collection("ipinfo").document(did).setData(["Wallpaper Image":wallpaperImageUrl], merge: true)
}
}
})
}

iOS How to load photo from camera to parse Swift

How can i load photo from camera or phone library to parse, like PFFile?
How to load image from assets i know, my code:
func loadImage() {
let query = PFQuery(className: "_User")
query.findObjectsInBackground { (objects, error) in
let firstObject = objects?.first as PFObject?
let objectFile = firstObject?.object(forKey: "avatar") as! PFFile
objectFile.getDataInBackground(block: { (imageData, error) in
let image = UIImage(data: imageData!)
if image != nil {
self.avatar.image = image
}
})
}
}
This code upload image from assets.
But i need upload from camera or library.
Try this.
call displayUploadImageDialog func on button click. it will open dialog and when you select any image from photos than below delegate method calls.
func displayUploadImageDialog(btnSelected: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
let alertController = UIAlertController(title: "", message: "Action on Upload", preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel action"), style: .cancel, handler: {(_ action: UIAlertAction) -> Void in
alertController.dismiss(animated: true) {() -> Void in }
})
alertController.addAction(cancelAction)
let takePhotoAction = UIAlertAction(title: NSLocalizedString("Take Photo", comment: "Take Photo action"), style: .default, handler: {(_ action: UIAlertAction) -> Void in
if UI_USER_INTERFACE_IDIOM() == .pad {
OperationQueue.main.addOperation({() -> Void in
picker.sourceType = .camera
self.present(picker, animated: true) {() -> Void in }
})
}
else {
if !UIImagePickerController.isSourceTypeAvailable(.camera) {
let passwordAlert = UIAlertController(title: "Error", message: "Device has no camera", preferredStyle: .alert)
let yesButton = UIAlertAction(title: "OK", style: .default, handler: {(_ action: UIAlertAction) -> Void in
//Handel your yes please button action here
passwordAlert.dismiss(animated: true) {() -> Void in }
})
passwordAlert.addAction(yesButton)
self.present(passwordAlert, animated: true) {() -> Void in }
}
else {
picker.sourceType = .camera
self.present(picker, animated: true) {() -> Void in }
}
}
})
alertController.addAction(takePhotoAction)
let cameraRollAction = UIAlertAction(title: NSLocalizedString("Camera Roll", comment: "Camera Roll action"), style: .default, handler: {(_ action: UIAlertAction) -> Void in
if UI_USER_INTERFACE_IDIOM() == .pad {
OperationQueue.main.addOperation({() -> Void in
picker.sourceType = .photoLibrary
self.present(picker, animated: true) {() -> Void in }
})
}
else {
picker.sourceType = .photoLibrary
self.present(picker, animated: true) {() -> Void in }
}
})
alertController.addAction(cameraRollAction)
alertController.view.tintColor = Colors.NavTitleColor
present(alertController, animated: true) {() -> Void in }
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var user = PFUser.current()
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageData = UIImageJPEGRepresentation(image, 0.05)
let imageFile = PFFile(name:"image.jpg", data:imageData!)
user!["profilePicture"] = imageFile;
user?.saveInBackground(block: nil)
self.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}

Why is my keyboard being loaded whenever I load my UIImagePickerController view?

I have a UIActionSheet for selecting between the camera or the photo library to embed an image into a UITextView but for whatever reason it's loading the keyboard. I force close the keyboard on press of the left button of the bar surrounding the UITextView but when I press photo library I opens and closes the keyboard before pushing to the image picker VC.
override func didPressLeftButton(sender: AnyObject?) {
let cameraMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let photoLibrary = UIAlertAction(title: "Photo Library", style: .Default, handler: { (UIAlertAction) in
self.openPhotoLibrary()
})
let takePhoto = UIAlertAction(title: "Open Camera", style: .Default, handler: { (UIAlertAction) in
self.textView.endEditing(true)
self.openCamera()
})
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
cameraMenu.addAction(photoLibrary)
cameraMenu.addAction(takePhoto)
cameraMenu.addAction(cancel)
self.presentViewController(cameraMenu, animated: true, completion: nil)
}
func openPhotoLibrary() {
imagePicker.sourceType = .PhotoLibrary
imagePicker.allowsEditing = false
presentViewController(imagePicker, animated: true, completion: nil)
}
func openCamera(){
imagePicker.sourceType = .Camera
imagePicker.showsCameraControls = true
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// Image resizing
let textViewWidth: CGFloat = self.textView.frame.size.width - 20
let percentResize = textViewWidth / pickedImage.size.width
let toBeExportedHeight = pickedImage.size.height * percentResize
let resizedImage = ImageManipulationManager.sharedInstance.resizeImage(exportedWidth: Int(textViewWidth),exportedHeight: Int(toBeExportedHeight), originalImage: pickedImage)
// Storage into TextView
let attachment = NSTextAttachment()
attachment.image = resizedImage
let attString = NSAttributedString(attachment: attachment)
textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location)
pastedImageLocations.append(textView.selectedRange.location)
textView.selectedRange.location = textView.selectedRange.location + 1
textView.textStorage.insertAttributedString(NSAttributedString(string: "\n"), atIndex: textView.selectedRange.location)
textView.selectedRange.location = textView.selectedRange.location + 1
textView.font = UIFont.systemFontOfSize(16.0)
// Image Caching
if let data = UIImageJPEGRepresentation(pickedImage, 0.50) {
socketMessages.append(["data": data])
haneke.set(value: data, key: String(unsafeAddressOf(attachment.image!)))
print("Image cached as \"\(String(unsafeAddressOf(attachment.image!)))\"")
}
}
dismissViewControllerAnimated(true, completion: nil)
self.textView.becomeFirstResponder()
}
Found the solution.
I had to change
dismissViewControllerAnimated(true, completion: nil)
self.textView.becomeFirstResponder()
to
dismissViewControllerAnimated(true) {
self.textView.becomeFirstResponder()
}
You can do some changes by adding this -
override func didPressLeftButton(sender: AnyObject?) {
let cameraMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let photoLibrary = UIAlertAction(title: "Photo Library", style: .Default, handler: { (UIAlertAction) in
self.view.endEditing(true) //**------ Add this
self.openPhotoLibrary()
})
let takePhoto = UIAlertAction(title: "Open Camera", style: .Default, handler: { (UIAlertAction) in
self.view.endEditing(true) //**------ Add this
self.openCamera()
})
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
cameraMenu.addAction(photoLibrary)
cameraMenu.addAction(takePhoto)
cameraMenu.addAction(cancel)
self.presentViewController(cameraMenu, animated: true, completion: nil)
}

Unable to pass image taken from camera to another viewcontroller

I have a button to take an image . I wish to pass the image taken from camera to another view controller.The code for first viewcontroller is shown below.
#IBAction func takePhoto(sender: AnyObject)
{ let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker, animated: true,completion : nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
TakenImage = info[UIImagePickerControllerOriginalImage] as? UIImage ; dismissViewControllerAnimated(true, completion: nil )
let controller = self.storyboard!.instantiateViewControllerWithIdentifier("NoteDetailViewController") as! NoteDetailViewController
controller.takinPhoto = true
if (note != "")
{
controller.content = note
}
controller.imageFromCamera = TakenImage
if (self.tags != "")
{
controller.tagsTextField.text = self.tags
}
self.presentViewController(controller, animated: true, completion: nil)
}
#IBAction func save(sender: AnyObject)
{
UIImageWriteToSavedPhotosAlbum(TakenImage!, self, "image:didFinishSavingWithError:contextInfo:", nil)
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>)
{
if error == nil {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
} else
{
let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
}
The code for my second viewcontroller is shown below
if (takinPhoto == true)
{
if (imageFromCamera != nil)
{
if let image1 = self.imageFromCamera
{
self.imageView2.image = image1
}
}
if (self.content != "")
{
self.contentTextField2.text = content
}
}
But image from camera is not appearing in the second viewcontroller.How can I solve this??
Updated answer.
I rewrote your code and was able to get it working locally. The main change was to use a different delegate method which is specific to photos.
#IBAction func takePhoto(sender: AnyObject) { let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .Camera
presentViewController(picker, animated: true,completion : nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
takenImage = image
dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func save(sender: AnyObject) {
UIImageWriteToSavedPhotosAlbum(takenImage!, self, #selector(ViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
if error == nil {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
} else {
let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "saveTakenImage") {
let controller = segue.destinationViewController as! NoteDetailViewController
controller.takinPhoto = true
if (note != "") {
controller.content = note
}
controller.imageFromCamera = takenImage
if (self.tags != "") {
controller.tagsTextField.text = self.tags
}
}
}

Resources