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)
}
Related
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)
}
}
I wanna add message to phone call alert popup.
how to make it?
enter image description here
Yes, you can do it like that:
func phoneCall(to phoneNumber:String) {
if let callURL:URL = URL(string: "tel:\(phoneNumber)") {
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(callURL)) {
let alert = UIAlertController(title: "Your Title", message: "Do you want call that number?", preferredStyle: .alert)
let callAction = UIAlertAction(title: "Call", style: .default, handler: { (action) in
application.openURL(callURL)
})
let noAction = UIAlertAction(title: "No", style: .cancel, handler: { (action) in
print("Canceled Call")
})
alert.addAction(callAction)
alert.addAction(noAction)
self.present(alert, animated: true, completion: nil)
}
}
}
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
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.
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 !