Swift 3 how to limit user to only taking photos and NOT videos - iOS, Xcode - swift

My photo app crashes when user selects video. The user can select photo and it works fine, but I'd like to remove the option to take a video. How do I disable video? The relevant chunk of code is below...
#IBAction func choosePhoto(_ sender: UIButton) {
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .actionSheet)
imagePicker = UIImagePickerController()
imagePicker.delegate = self
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
let cameraAction = UIAlertAction(title: "Use Camera", style: .default) { (action) in
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if (status == .authorized) {
self.displayPicker(type: .camera)
}
if (status == .restricted) {
self.handleRestricted()
}
if (status == .denied) {
self.handleDenied()
}
if (status == .notDetermined) {
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted) in
if (granted) {
self.displayPicker(type: .camera)
}
})
}
}
alertController.addAction(cameraAction)
}
if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
let photoLibraryAction = UIAlertAction(title: "Use Photo Library", style: .default) { (action) in
let status = PHPhotoLibrary.authorizationStatus()
if (status == .authorized) {
self.displayPicker(type: .photoLibrary)
}
if (status == .restricted) {
self.handleRestricted()
}
if (status == .denied) {
self.handleDenied()
}
if (status == .notDetermined) {
PHPhotoLibrary.requestAuthorization({ (status) in
if (status == PHAuthorizationStatus.authorized) {
self.displayPicker(type: .photoLibrary)
}
})
}
}
alertController.addAction(photoLibraryAction)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
func handleDenied() {
let alertController = UIAlertController(title: "Camera Access Denied", message: "This app does not have acces to your device's camera. Please update your settings.", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Go To Settings", style: .default) { (action) in
DispatchQueue.main.async {
UIApplication.shared.open(NSURL(string: UIApplicationOpenSettingsURLString)! as URL)
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.popoverPresentationController?.sourceView = self.photoImage
alertController.popoverPresentationController?.sourceRect = self.photoImage.bounds
alertController.addAction(settingsAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
func handleRestricted() {
let alertController = UIAlertController(title: "Camera Access Denied", message: "This device is restricted from accessing the camera at this time", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.popoverPresentationController?.sourceView = self.photoImage
alertController.popoverPresentationController?.sourceRect = self.photoImage.bounds
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
}
func displayPicker(type: UIImagePickerControllerSourceType) {
self.imagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: type)!
self.imagePicker.sourceType = type
self.imagePicker.allowsEditing = true
DispatchQueue.main.async {
self.present(self.imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage
photoImage.contentMode = .scaleAspectFill
photoImage.image = chosenImage
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}

Put this line right after imagePicker.delegate = self
imagePicker.mediaTypes = [kUTTypeImage as String]
Remember to add import MobileCoreServices at the beginning of the file.

What you want to do is after you init imagePicker set the following property
imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeCamera];
https://developer.apple.com/documentation/uikit/uiimagepickercontroller/1619173-mediatypes

Related

Image Uploading by using PHPhoto Libary and alamofire in swift

var imageAssets = [PHAsset]()
I am trying to upload image using Alamofire multipart.After picking image from library, i am storing it in "imageAssets". and uploading the image . In following code, two functions are there .
func multiImageUpload(userId: Int) and func changeProfilePicAction()
changeProfileAction function is for selecting image from gallery and multiImageUpload function is to upload these image to server.
multipartFormData.append(image!.jpegData(compressionQuality: 0.2)!, withName: "fileset",fileName: "file\(i).jpg", mimeType: "image/jpg").
When i am executing above code, the image is loading but with name like - "file.jpg", "file1.jpg", "file2.jpg", "file3.jpg" . But i want to send the properImage name to the server . How to do this ?
private func multiImageUpload(userId: Int) {
print(userId)
let url = myUrl
let headers: HTTPHeaders = headers
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append("\(userId)".data(using: String.Encoding.utf8)!, withName: "UserId" as String)
for i in 1...self.imageAssets.count-1{
PHImageManager.default().requestImage(for: self.imageAssets[i], targetSize: CGSize.zero, contentMode: .default, options: nil, resultHandler: { (image, info) in
print(image!)
print( self.selectedProfilePic.image!)
if image! == self.selectedProfilePic.image!{
print("exclude \(String(describing: image))")
print("exclude i = \(i)")
}
else{
multipartFormData.append(image!.jpegData(compressionQuality: 0.2)!, withName: "fileset",fileName: "file\(i).jpg", mimeType: "image/jpg")
print("i = \(i)")
}
})
}
}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print(response)
print("Succesfully uploaded")
if let err = response.error{
print(err.localizedDescription)
return
}
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
}
}
}
// profile image selection
func changeProfilePicAction(){
let status = PHPhotoLibrary.authorizationStatus()
if (status == PHAuthorizationStatus.authorized) {
let actionSheet = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction.init(title: "Camera", style: .default, handler: { (UIAlertAction) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
let picker = UIImagePickerController()
picker.sourceType = .camera
picker.allowsEditing = true
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
else{
}
}))
actionSheet.addAction(UIAlertAction.init(title: "Gallery", style: .default, handler: { (UIAlertAction) in
self.vc = BSImagePickerViewController()
self.bs_presentImagePickerController(self.vc!, animated: true,
select: { (asset: PHAsset) -> Void in
}, deselect: { (asset: PHAsset) -> Void in
}, cancel: { (assets: [PHAsset]) -> Void in
}, finish: { (assets: [PHAsset]) -> Void in
self.imageAssets = assets
self.multipleImageView.isHidden = false
self.view.bringSubviewToFront(self.multipleImageView)
self.setSelectedProfileImages(index: 0)
self.multipleProfilePicCV.reloadData()
//self.tableView.reloadData()
}, completion: nil)
}))
actionSheet.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
} else if (status == PHAuthorizationStatus.denied) {
let alertController = UIAlertController(title: Common.sharedInstance().TITLE_ALERT, message: "Kismet would like to access your photo library, To display your profile picture to other Kismet users.", preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertAction.Style.default,handler: nil))
alertController.addAction(UIAlertAction(title: "Setting", style: .default, handler: { (alertAction) in
if let appSettings = URL(string: UIApplication.openSettingsURLString) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(appSettings, options: [:], completionHandler: nil)
} else {
}
}
}))
self.present(alertController, animated: true, completion: nil)
}
else {
PHPhotoLibrary.requestAuthorization({ (newStatus) in
if (newStatus == PHAuthorizationStatus.authorized) {
let picker = UIImagePickerController()
picker.sourceType = .photoLibrary
picker.allowsEditing = true
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
else {
DispatchQueue.main.async {
let alertController = UIAlertController(title: Common.sharedInstance().TITLE_ALERT, message: "Kismet would like to access your photo library, To display your profile picture to other Kismet users.", preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertAction.Style.default,handler: nil))
alertController.addAction(UIAlertAction(title: "Setting", style: .default, handler: { (alertAction) in
if let appSettings = URL(string: UIApplication.openSettingsURLString) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(appSettings, options: [:], completionHandler: nil)
} else {
}
}
}))
self.present(alertController, animated: true, completion: nil)
}
}
})
}
}

Firebase Phone Auth Swift

I would like to add the ability to register with the phone number while registering. I wrote a function but it doesn't work. Can you examine the code? What should I do?
func sendCode(_ sender: Any) {
let alert = UIAlertController(title: "Phone number", message: "Is this your phone number? \n \(emailField.text!)", preferredStyle: .alert)
let action = UIAlertAction(title: "Yes", style: .default) { (UIAlertAction) in
PhoneAuthProvider.provider().verifyPhoneNumber(self.emailField.text!, uiDelegate: nil) { (verificationID, error) in
if error != nil {
print("eror: \(String(describing: error?.localizedDescription))")
} else {
let defaults = UserDefaults.standard
defaults.set(verificationID, forKey: "authVID")
let navController = UINavigationController(rootViewController: CodeEntryView())
self.present(navController, animated: true, completion: {
})
}
}
}
let cancel = UIAlertAction(title: "No", style: .cancel, handler: nil)
alert.addAction(action)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}

Unable to merge two firebase arrays in Firebase Database

Hello I am relatively new to Swift/Firebase and I am struggling to merge two arrays so that the downloadURL is seen amongst both the name and the email fields. One function adds the name and the email through the button click the other is another function to save the URL. When I try and merge them I get this (as seen in the image below). Here is my code:
#IBAction func createAccountAction(_ sender: AnyObject) {
let Users = Database.database().reference().child("Users")
let userDictionary : NSDictionary = ["email" : emailTextField.text as String!, "Name": nameTextField.text!]
Users.childByAutoId().setValue(userDictionary) {
(error, ref) in
if self.emailTextField.text == "" {
let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
Auth.auth().createUser(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in
if error == nil {
print("You have successfully signed up")
//Goes to the Setup page which lets the user take a photo for their profile picture and also chose a username
var imgData: NSData = NSData(data: UIImageJPEGRepresentation((self.profilePicture?.image)!, 0.8)!)
self.uploadProfileImageToFirebase(data: imgData)
let vc = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.present(vc, animated: true, completion: nil)
} else {
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
}
func addImageURLToDatabase(uid:String, values:[String:AnyObject]){
let Users = Database.database().reference().child("Users")
let ref = Database.database().reference(fromURL: "https://example.firebaseio.com/")
Users.updateChildValues(values) { (error, ref) in
if(error != nil){
print(error)
return
}
self.parent?.dismiss(animated: true, completion: nil)
}
}
Something like this is what you want. I removed a few variables from your function but you can add them back. I just wanted to make sure the code compiles.
#IBAction func createAccountAction(_ sender: AnyObject) {
let usersRef = Database.database().reference().child("Users")
let userDictionary : NSDictionary = ["email" : emailTextField.text!, "Name": nameTextField.text!]
if emailTextField.text == "" {
let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
Auth.auth().createUser(withEmail: self.emailTextField.text ?? "", password: self.passwordTextField.text ?? "") { (result, error) in
if error != nil {
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
return
}
guard let user = result?.user else { return }
// HERE YOU SET THE VALUES
usersRef.child(user.uid).setValue(userDictionary, withCompletionBlock: { (error, ref) in
if error != nil { print(error); return }
self.addImageURLToDatabase(uid: user.uid, values: ["Put": "Your Values Here" as AnyObject])
})
}
}
}
func addImageURLToDatabase(uid:String, values:[String:AnyObject]){
let usersRef = Database.database().reference().child("Users").child(uid)
usersRef.updateChildValues(values) { (error, ref) in
if(error != nil){
print(error)
return
}
self.parent?.dismiss(animated: true, completion: nil)
}
}

UIImagePickerControllerDelegate error

So I have this code that will get photos my gallery or use the camera to change the UIImage.
#IBAction func tappedCamera() {
print("tapped camera")
let optionMenu = UIAlertController(title: nil, message: "Choose Option", preferredStyle: .actionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
self.picker.sourceType = UIImagePickerControllerSourceType.camera;
self.picker.allowsEditing = true
self.present(self.picker, animated: true, completion: nil)
}
})
let galleryAction = UIAlertAction(title: "Gallery", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
self.picker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
self.picker.allowsEditing = true
self.present(self.picker, animated: true, completion: nil)
}
})
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
//do none
})
optionMenu.addAction(cameraAction)
optionMenu.addAction(galleryAction)
optionMenu.addAction(cancelAction)
self.present(optionMenu, animated: true, completion: nil)
}
But I always get this error, whenever I try to capture a photo or select an image from the gallery.
[Generic] Creating an image format with an unknown type is an error
I solved it by fixing my user defaults. Because somewhere along the code I was messing up with the images, converting them to base64 strings, then saving it to user defaults.

crop square image after get app gallary

I am new in swift. I made simple iphone app. Use this link: http://www.oodlestechnologies.com/blogs/Open-Image-Gallery-and-Take-photo-in-Swift and my app worked perfect. I want my app to select cropable image like facebook or telegram.
Like this:
My code:
private func showBottomActionSheet(){
let chooseOptionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let takePhotoAction = UIAlertAction(title: "Take Photo", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
self.openCamera()
})
let choosePhotoAction = UIAlertAction(title: "Choose Photo", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
self.openGallary()
})
let findImagesAction = UIAlertAction(title: "Find Images", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
print("Clicked Find Images")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancelled")
})
chooseOptionMenu.addAction(takePhotoAction)
chooseOptionMenu.addAction(choosePhotoAction)
chooseOptionMenu.addAction(findImagesAction)
chooseOptionMenu.addAction(cancelAction)
self.presentViewController(chooseOptionMenu, animated: true, completion: nil)
}
private func openGallary()
{
self.picker!.allowsEditing = false
self.picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
presentViewController(picker!, animated: true, completion: nil)
}
private func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
self.picker!.allowsEditing = false
self.picker!.sourceType = UIImagePickerControllerSourceType.Camera
self.picker!.cameraCaptureMode = .Photo
presentViewController(self.picker!, animated: true, completion: nil)
}else{
let alert = UIAlertController(title: "Camera Not Found", message: "This device has no Camera", preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style:.Default, handler: nil)
alert.addAction(ok)
presentViewController(alert, animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
self.choosenPhoto = chosenImage
DefaultUser.setUserImage(chosenImage)
dismissViewControllerAnimated(true, completion: nil)
}
I found objective c code but didn't find code for swift 2.
Plz, advise me. thanks !