3
Good morning guys, I am developing an application in Swift, but I am new in the language and do not know some things, I would like to know how I attach the images from my gallery or open the mobile camera to take a photo.
Thanks in advance.
3
Good morning guys, I am developing an application in Swift, but I am new in the language and do not know some things, I would like to know how I attach the images from my gallery or open the mobile camera to take a photo.
Thanks in advance.
0
Whoa, whoa, whoa, whoa? follows the code to do that action, native to Ios, does not spend adding any lib.
import UIKit
import Firebase
import APESuperHUD
class CadastroEleitorViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var txtNome: UITextField!
var nome: String!
@IBOutlet weak var txtSobrenome: UITextField!
var sobrenome: String!
@IBOutlet weak var txtEmail: UITextField!
var email: String!
@IBOutlet weak var txtSenha: UITextField!
var senha: String!
@IBOutlet weak var imagemPerfil: UIImageView!
var imagem : UIImage!
var mEleitorModel = EleitorModel()
var ref: DatabaseReference!
var userID : String!
override func viewDidLoad() {
super.viewDidLoad()
if FirebaseApp.app() == nil {
FirebaseApp.configure()
}
ref = Database.database().reference()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imagem = info[UIImagePickerControllerOriginalImage] as! UIImage
imagemPerfil.image = imagem
imagemPerfil.layer.borderWidth = 1.0
imagemPerfil.layer.masksToBounds = false
imagemPerfil.layer.borderColor = UIColor.white.cgColor
imagemPerfil.layer.cornerRadius = imagemPerfil.frame.size.width / 2
imagemPerfil.clipsToBounds = true
dismiss(animated: true, completion: nil)
}
@IBAction func botaoTirarFoto(_ sender: Any) {
capturaFoto()
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return.lightContent // barra de status tema claro
}
@IBAction func iconeVoltar(_ sender: Any) {
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
}
@IBAction func botaoCadastrar(_ sender: Any) {
if validaCampos() {
FunctionDefault.exibeProgress(mensagem: "Carregando...")
criaUsuario()
}
}
@IBAction func botaoCadastrarFacebook(_ sender: Any) {
let storyboard = UIStoryboard(name: "Usuario", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "PagamentoViewController") as UIViewController
present(vc, animated: true, completion: nil)
}
@IBAction func botaoLogin(_ sender: Any) {
telaLogin()
}
func validaCampos() -> Bool {
nome = txtNome.text?.trimmingCharacters(in: .whitespacesAndNewlines)
sobrenome = txtSobrenome.text?.trimmingCharacters(in: .whitespacesAndNewlines)
email = txtEmail.text?.trimmingCharacters(in: .whitespacesAndNewlines)
senha = txtSenha.text?.trimmingCharacters(in: .whitespacesAndNewlines)
if nome.isEmpty {
FunctionDefault.AlertMessage(title: "Alerta", message: "Por favor informe seu nome!", targetVC: self)
return false
}
if sobrenome.isEmpty {
FunctionDefault.AlertMessage(title: "Alerta", message: "Por favor informe seu sobrenome!", targetVC: self)
return false
}
if email.isEmpty {
FunctionDefault.AlertMessage(title: "Alerta", message: "Por favor informe seu e-mail!", targetVC: self)
return false
}
if senha.isEmpty {
FunctionDefault.AlertMessage(title: "Alerta", message: "Por favor informe uma senha!", targetVC: self)
return false
}
if senha.count < 6 {
FunctionDefault.AlertMessage(title: "Alerta", message: "Senha muito curta, digite no mínimo 6 caracteres!", targetVC: self)
return false
}
if imagem == nil {
let alert = UIAlertController(title: "Foto do perfil", message: "Vamos adicionar uma foto ao seu perfil para que todos possam te identificar.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Selecionar foto", style: UIAlertActionStyle.default, handler: { (action) in
self.capturaFoto()
}))
self.present(alert, animated: true, completion: nil)
return false
}
return true
}
func uploadImage() -> Void {
let storage = Storage.storage()
let nomeImagem = self.nome + ".jpg"
let storageRef = storage.reference().child("App/Eleitores").child(userID).child("ImagemPerfil").child(nomeImagem)
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
if let uploadData = UIImageJPEGRepresentation(self.imagemPerfil.image!, 0.2){
storageRef.putData(uploadData, metadata: metadata, completion: { (metadata, error) in
if error == nil{
storageRef.downloadURL { url, error in
if error != nil {
// Handle any errors
} else {
self.mEleitorModel.urlFotoPerfil = url?.absoluteString
self.gravaUsuario()
}
}
}
})
}
}
func criaUsuario() -> Void {
Auth.auth().createUser(withEmail: email, password: senha) { (user, error) in
if error == nil {
self.userID = Auth.auth().currentUser!.uid
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
let dataAtual = formatter.string(from: date)
self.mEleitorModel.id = self.userID
self.mEleitorModel.nome = self.nome + " " + self.sobrenome
self.mEleitorModel.email = self.email
self.mEleitorModel.dataCadastro = dataAtual
self.uploadImage()
}
else{
if error.debugDescription.contains("The email address is already in use by another account."){
let alert = UIAlertController(title: "Atenção", message: "Este email já consta em nosso cadastro, efetue o login ou relembre sua senha.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Relembrar Senha", style: UIAlertActionStyle.default, handler: { (action) in
self.telaAlterarSenha()
}))
alert.addAction(UIAlertAction(title: "Login", style: UIAlertActionStyle.default, handler: { (action) in
self.telaLogin()
}))
self.present(alert, animated: true, completion: nil)
}
FunctionDefault.dismissProgrees()
FunctionDefault.AlertMessage(title: "Erro", message: "Ocorreu uma falha ao processar seu pedido, revise seus dados e tente novamente!", targetVC: self)
}
}
}
func gravaUsuario() -> Void {
let encodedObject = try? JSONEncoder().encode(self.mEleitorModel)
let jsonObject = String(data: encodedObject!, encoding: .utf8)
let dict = FunctionDefault.convertToDictionary(text: jsonObject!)
self.ref.child("eleitores").child(userID).setValue(dict)
FunctionDefault.dismissProgrees()
//TODO: tratar proxima tela
}
func capturaFoto() -> Void {
let controller = UIImagePickerController()
controller.delegate = self
controller.sourceType = .photoLibrary
present(controller, animated: true, completion: nil)
}
func telaLogin() -> Void {
let storyboard = UIStoryboard(name: "Usuario", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "LoginViewController") as UIViewController
present(vc, animated: true, completion: nil)
}
func telaAlterarSenha() -> Void {
let storyboard = UIStoryboard(name: "Usuario", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "AlterarSenhaViewController") as UIViewController
present(vc, animated: true, completion: nil)
}
}
0
You can make a giant code in your hand or use a pod, which is what I recommend. I’ve used the Alcameraviewcontroller pod, which makes it possible to take both photos and choose from the gallery. You can find his github here:
https://github.com/AlexLittlejohn/ALCameraViewController
Steps to use:
1) Add to your podfile:
pod 'ALCameraViewController'
2) Import into your file that will call the camera’s view controller the pod, with the following line:
import ALCameraViewController
3) When calling the camera’s view controller use the following code:
let cameraViewController = CameraViewController { [weak self] image, asset in
// A variável image que você recebe aqui vai ter a imagem que o usuário escolheu. Fique atento para o caso que ele cancela a escolha da imagem.
self?.dismiss(animated: true, completion: nil)
}
present(cameraViewController, animated: true, completion: nil)
For more tips on swif, iOS development and entrepreneurship subscribe to my youtube channel: https://www.youtube.com/channel/UCNghEgS-PkKMDbZfiwhvYpA
Browser other questions tagged swift
You are not signed in. Login or sign up in order to post.