'StorageMetadata' has no member 'downloadURL' - ios

So, I've gotten 2 more errors in my code which I've tried to solve for a while for my school project, but since I'm not used to programming in swift I haven't been able to solve it (I've taken code from a youtube tutorial). The first one is "Value of 'StorageMetaData' has no member 'downloadURL' (inside the func uploadImg). Then the other erros is "use of unresolved identifier 'imagePicker' (at the end of #IBAction func selectedImgPicker".
Here's my code:
class SignUpVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var userImagePicker: UIImageView!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var signUpBtn: UIButton!
var userUid: String!
var emailField: String!
var passwordField: String!
var imagePicker: UIImagePickerController!
var imageSelected = false
var username: String!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
}
override func viewDidDisappear(_ animated: Bool) {
if let _ = KeychainWrapper.standard.string(forKey: "uid"){
performSegue(withIdentifier: "Message", sender: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
if let image = info[UIImagePickerControllerEditedImage] as? UIImage{
userImagePicker.image = image
imageSelected = true
} else {
print("image wasnt selected")
}
imagePicker.dismiss(animated: true, completion: nil)
}
func setUser(img: String){
let userData = ["username": username!, "userImg": img]
KeychainWrapper.standard.set(userUid, forKey: "uid")
let location = Database.database().reference().child("users").child(userUid)
location.setValue(userData)
dismiss(animated: true, completion: nil)
}
func uploadImg(){
if usernameField.text == nil {
signUpBtn.isEnabled = false
} else {
username = usernameField.text
signUpBtn.isEnabled = true
}
guard let img = userImagePicker.image, imageSelected == true else{
print("image needs to be selected")
return
}
if let imgData = UIImageJPEGRepresentation(img, 0.2){
let imgUid = NSUUID().uuidString
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
Storage.storage().reference().putData(imgData, metadata: metadata){
(metadata, error) in
if error != nil{
print("did not upload image")
}else{
print("uploaded")
let downloadURL = metadata?.downloadURL()?.absoluteString
if let url = downloadURL{
self.setUser(img: url)
}
}
}
}
}
#IBAction func createAccount(_ sender: AnyObject){
Auth.auth().createUser(withEmail: emailField, password: passwordField, completion: {
(user, error) in
if error != nil {
print("Cant create user")
} else {
if let user = user {
self.userUid = user.user.uid
}
}
self.uploadImg()
})
}
#IBAction func selectedImgPicker (_ sender: AnyObject){
present(imagePicker, animated: true, completion: nil)
}
#IBAction func cancel (_ sender: AnyObject){
dismiss(animated: true, completion: nil)
}
}

Related

Merge user info email/phone number authentication, Firebase firestore with swift

Create a user with Username, email, and password. Then force the user to complete phone number verification before the account is created.
I am designing an app where we would like to make the user sign up by creating a username, password, supply their email address, and then complete phone number verification.
This picture represents the desired flow we would like our user to complete to register their account.
here are our View Controller files:
This is the code for the "Create Account" view, it creates a user in Firebase using email
import UIKit
class CreateAccountVC: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var usernameTextfield: UITextField!
#IBOutlet weak var passwordTextfield: UITextField!
#IBOutlet weak var emailTextfield: UITextField!
#IBOutlet weak var confirmPasswordTextfield: UITextField!
#IBOutlet weak var createAccountLbl: UILabel!
#IBOutlet weak var createAccountTextView: UILabel!
#IBOutlet weak var signupBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:UIResponder.keyboardWillHideNotification, object: nil)
overrideUserInterfaceStyle = .light
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
signupBtn.clipsToBounds = true
signupBtn.layer.cornerRadius = 15
signupBtn.addButtonGradient(didType: true)
}
#objc func keyboardWillShow(notification:NSNotification){
let userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
scrollView.contentInset = contentInset
}
#objc func keyboardWillHide(notification:NSNotification){
let contentInset:UIEdgeInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInset
}
#IBAction func alreadyHaveAccountBtnPressed(_ sender: Any) {
// dismiss(animated: true, completion: nil)
// self.performSegue(withIdentifier: "TypePhoneNumberVC", sender: self)
}
#IBAction func signupBtnPressed(_ sender: Any) {
let username = usernameTextfield.text
let email = emailTextfield.text
let password = passwordTextfield.text
signupBtn.isHidden = true
AuthorizationService.instance.registerUser(username: username!, email: email!, password: password!) { (success, err) in
if success{
AuthorizationService.instance.loginUser(withEmail: email!, andPassword: password!) { (success, err) in
if err != nil{
return
}
self.performSegue(withIdentifier: "EnterNumberSegue", sender: self)
print("Sign-up successful")
}
}else{
let alertController = UIAlertController(title: "Error", message: err?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
self.signupBtn.isHidden = false
}
}
}
#IBAction func backBtnPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
These next two demonstrate the implementation of the Phone number verification
import UIKit
import Firebase
import FirebaseAuth
class EnterPhoneNumberVC: UIViewController, UITextFieldDelegate{
#IBOutlet weak var backButton: UIButton!
#IBOutlet weak var phoneNumberUITextField: UITextField!
#IBOutlet weak var getCodeButton: UIButton!
let userDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
phoneNumberUITextField.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(handle))
view.addGestureRecognizer(tap)
overrideUserInterfaceStyle = .light
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getCodeButton.clipsToBounds = true
getCodeButton.layer.cornerRadius = 15
getCodeButton.addButtonGradient(didType: true)
}
#objc func handle(tap: UITapGestureRecognizer){
view.endEditing(true)
}
#IBAction func backButtonPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
#IBAction func getCodeButtonPressed(_ sender: Any) {
guard let phoneNumber = phoneNumberUITextField.text else {return}
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
if error == nil {
print(verificationID)
guard let verifyID = verificationID else {return}
self.userDefaults.set(verifyID, forKey:"verificationID")
self.userDefaults.synchronize()
self.performSegue(withIdentifier: "GetCodeSegue", sender: self)
} else {
print("unable to confirm the users phone number", error?.localizedDescription)
}
}
}
import UIKit
import Firebase
import FirebaseAuth
class PhoneNumberVerificationVC: UIViewController, UITextFieldDelegate {
#IBOutlet weak var verifyBtn: UIButton!
#IBOutlet weak var resendCodeBtn: UIButton!
#IBOutlet weak var otpCode: UITextField!
var verificationID: String?
let userDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
let tap = UITapGestureRecognizer(target: self, action: #selector(handle))
view.addGestureRecognizer(tap)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
verifyBtn.clipsToBounds = true
verifyBtn.layer.cornerRadius = 15
verifyBtn.addButtonGradient(didType: true)
}
#objc func handle(tap: UITapGestureRecognizer){
view.endEditing(true)
}
#IBAction func backBtnPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
#IBAction func verifyBtnPressed(_ sender: Any) {
guard let optCode = otpCode.text else {return}
guard let verificationID = userDefaults.string(forKey: "verificationID") else {return}
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID, verificationCode: optCode)
Auth.auth().signInAndRetrieveData(with: credential) { (success, error) in
if error == nil {
print(success)
self.performSegue(withIdentifier: "VerifiedSegue", sender: self)
print("The user has successfully logged In and is verified!")
} else {
print("Error: Phone number and One time password does not match")
}
}
}

How to Crop iPhone Image in Swift 3 App

I am currently in the process of creating a camera app, however when someone takes a picture and it goes to the the crop screen, it doesn't actually fit it to that specific size. How can I change my code to make it only spit out a 800x800 image?
import UIKit
import Firebase
class CameraControllerViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var postBtn: UIButton!
#IBOutlet weak var pickedimage: UIImageView!
#IBOutlet weak var libBtn: UIButton!
#IBOutlet weak var camBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func camerabuttonaction(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated:true, completion: nil)
}
}
#IBAction func photolibraryaction(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
#IBAction func saveaction(_ sender: Any) {
let imageData = UIImageJPEGRepresentation(pickedimage.image!, 0.6)
let compressedJPEGImage = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(compressedJPEGImage!, nil, nil, nil)
saveNotice()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]! ) {
pickedimage.image = image
camBtn.isHidden = true
libBtn.isHidden = true
postBtn.isHidden = false
self.dismiss(animated: true, completion: nil);
}
func saveNotice() {
AppDelegate.instance().showActivityIndicator()
//let alertController = UIAlertController(title: "Image Saved", message: "Your picture was saved.", preferredStyle: .alert)
//let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
//alertController.addAction(defaultAction)
//present(alertController, animated: true, completion: nil)
let uid = Auth.auth().currentUser!.uid
let ref = Database.database().reference()
let storage = Storage.storage().reference(forURL: "gs://new-glaance.appspot.com")
let key = ref.child("posts").childByAutoId().key
let imageRef = storage.child("posts").child(uid).child("\(key).jpg")
let data = UIImageJPEGRepresentation(self.pickedimage.image!, 0.6)
let uploadTask = imageRef.putData(data!, metadata: nil) { (metadata,error) in
if error != nil {
print(error!.localizedDescription)
AppDelegate.instance().dismissActivityIndicator()
return
}
imageRef.downloadURL(completion: { (url, error) in
if let url = url {
let feed = ["userID": uid,
"pathToImage": url.absoluteString,
"likes":0,
"author": Auth.auth().currentUser!.displayName!,
"postID": key] as [String: Any]
let postFeed = ["\(key)":feed]
ref.child("posts").updateChildValues(postFeed)
AppDelegate.instance().dismissActivityIndicator()
}
})
}
uploadTask.resume()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I don't know of a way to constrain a crop to a particular aspect ratio. Instead I'd suggest creating your own method for cropping images.
I have an app on Github called CropImg that does just that. It doesn't constrain the crop to square, but that would be easy to add.

Profile page swift 3 errors

This is the code that I have created for my profile page but it has some mistakes that i would like to adjust.
import UIKit
import FirebaseStorage
import FirebaseDatabase
import FirebaseAuth
import Firebase
class ProfileClass: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var userImagePicker: RoundButton!
#IBOutlet weak var ProfilePicture: RoundImage!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var imageLoader: UIActivityIndicatorView!
var loggedInUser = AnyObject?()
var databaseRef = FIRDatabase.database().reference()
var storageRef = FIRStorage.storage().reference()
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
self.loggedInUser = FIRAuth.auth()?.currentUser
self.databaseRef.child("user_profile").child(self.loggedInUser!.uid).observeSingleEvent(of: FIRDataEventType(.Value) { (snapshot:FIRDataSnapshot) in
if(snapshot.value!["usernameField"] !== nil) {
self.usernameField.text = snapshot.value!["usernameField"] as? String
}
if(snapshot.value!["profile_pic"] !== nil) {
let databaseProfilePic = snapshot.value!["profile_pic"]
as! String
let data = NSData(contentsOfURL: NSURL(string: databaseProfilePic)!)
self.setProfilePicture(self.ProfilePicture,imageToSet:UIImage(data:data!)!)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func logoutTapped(_ sender: Any) {
let firebaseAuth = FIRAuth.auth()
do {
try firebaseAuth?.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
self.performSegue(withIdentifier: "goToLogin", sender: self)
}
#IBAction func TapProfileButton(_ sender: RoundButton) {
let myActionShett = UIAlertController(title:"Profile Picture",message:"Select",preferredStyle: UIAlertControllerStyle.actionSheet)
let viewPicture = UIAlertAction(title: "View Picture", style: UIAlertActionStyle.default) { (action) in
let imageView = sender.view as! RoundImage
let newImageView = RoundImage(image: imageView.image)
newImageView.frame = self.view.frame
newImageView.backgroundColor = UIColor.blackColor()
newImageView.contentMode = .scaleAspectFit
newImageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target:self,action:#selector(self.dismissFullScreenImage))
newImageView.addGestureRecognizer(tap)
self.view.addSubview(newImageView)
}
let photoGallery = UIAlertAction(title: "Photos", style: UIAlertActionStyle.default) { (action) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum)
{
self.imagePicker.delegate = self
self.imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
self.imagePicker.allowsEditing = true
self.present(self.imagePicker, animated: true, completion: nil)
}
}
let camera = UIAlertAction(title: "Camera", style: UIAlertActionStyle.default)
{ (action) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
{
self.imagePicker.delegate = self
self.imagePicker.sourceType = UIImagePickerControllerSourceType.camera
self.imagePicker.allowsEditing = true
self.present(self.imagePicker, animated: true, completion: nil)
}
}
myActionShett.addAction(viewPicture)
myActionShett.addAction(photoGallery)
myActionShett.addAction(camera)
myActionShett.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
self.present(myActionShett, animated: true, completion: nil)
}
func dismissFullScreenImage(sender:UITapGestureRecognizer)
{
sender.view?.removeFromSuperview()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.imageLoader.stopAnimating()
setProfilePicture(self.ProfilePicture,imageToSet: image)
if let imageData: NSData = UIImagePNGRepresentation(self.ProfilePicture, image!)!
{
let profilePicStorageRef = storageRef.child("user_profiles/\(self.loggedInUser!.uid)/profile_pic")
let uploadTask = profilePicStorageRef.putData(imageData, metadata: nil)
{metadata,error in
if(error == nil)
{
let downloadUrl = metadata!.downloadUrl()
self.databaseRef.child("user_profile").child(self.loggedInUser!.uid).child("profile_pic").setValue(downloadUrl!.absoluteString)
}
else
{
print(error?.localizedDescription)
}
self.imageLoader.stopAnimating()
}
}
self.dismiss(animated: true, completion: nil)
}
}
You have to give proper type. You can not initialize object of type AnyObject. and Obviously with not using AnyObject?.

Unresolved identifier error 'email'

This is related to a previous question that was solved (See here: Sharing variables). I saw nothing that addresses what to do if your variable still isn't being recognized but your code to pass the variable appears solid.
I'm getting an unresolved identifier error 'email' when attempting to utilize a user's email address as part of a file path to upload an image to Firebase Storage. Code is here:
import UIKit
import Firebase
import MobileCoreServices
import FirebaseStorage
class ThirdViewController: UIViewController {
#IBOutlet weak var uploadButton: UIButton!
#IBOutlet weak var progressView: UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named:"Book Funnel")!)
// Do any additional setup after loading the view.
}
#IBAction func uploadButtonWasPressed(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String, kUTTypeMovie as String]
imagePicker.delegate = self
self.present(imagePicker, animated: true, completion: nil)
}
func uploadImageToFirebaseStorage(data: NSData) {
let storageRef = FIRStorage.storage().reference(withPath: email/"/image.jpg")
let uploadMetadata = FIRStorageMetadata()
uploadMetadata.contentType = "image/jpeg"
let uploadTask = storageRef.put(data as Data, metadata: uploadMetadata) { (metadata, error) in
_ = metadata?.downloadURL
if (error != nil) {
print("I recieved an error! \(error?.localizedDescription)")
} else {
print ("Upload complete! Here's some metadata! \(metadata)")
}
let alert = UIAlertController(title: "Success!", message: "Image uploaded", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "okay", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
uploadTask.observe(.progress) { [weak self] (snapshot) in
guard let strongSelf = self else { return }
guard let progress = snapshot.progress else { return }
strongSelf.progressView.progress = Float(progress.fractionCompleted)
}
}
var toPass: String!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension ThirdViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let mediaType: String = info[UIImagePickerControllerMediaType] as? String else {
dismiss(animated: true, completion: nil)
return
}
if mediaType == (kUTTypeImage as String) {
if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage, let imageData = UIImageJPEGRepresentation(originalImage, 0.8) {
uploadImageToFirebaseStorage(data: imageData as NSData)
}
} else {
print("Please select an image")
}
dismiss(animated: true, completion: nil)
func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "segueTest") {
//Checking identifier is crucial as there might be multiple
// segues attached to same view
if let fourthVC = segue.destination as? FourthViewController {
fourthVC.toPass = "email"
}
}
}
}
}

Segue to next view controller after successful sign up

I've searched and searched and searched but not found a solution. The sign up works but will not segue to the next view controller. Heres my code:
import UIKit
import Parse
import Bolts
class SignUpVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var profilePictureIV: UIImageView!
#IBOutlet weak var firstNameTF: UITextField!
#IBOutlet weak var lastNameTF: UITextField!
#IBOutlet weak var newUsernameTF: UITextField!
#IBOutlet weak var newPasswordTF: UITextField!
#IBOutlet weak var emailTF: UITextField!
#IBOutlet weak var phoneNumberTF: UITextField!
#IBAction func setProfilePicture(sender: AnyObject) {
let myPickerController = UIImagePickerController()
myPickerController.delegate = self
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
#IBAction func signUpButton(sender: AnyObject) {
let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
if firstNameTF.text != "" && lastNameTF.text != "" && newUsernameTF.text != "" && newPasswordTF.text != "" && emailTF.text != "" && phoneNumberTF.text != "" {
let newUser = PFUser()
if let profilePictureImage = profilePictureIV?.image {
let profilePicture = UIImageJPEGRepresentation(profilePictureImage, 1)!
let profilePictureImageFile = PFFile(data: profilePicture)
newUser["profilePicture"] = profilePictureImageFile
}
newUser["firstName"] = firstNameTF.text
newUser["lastName"] = lastNameTF.text
newUser.username = newUsernameTF.text
newUser.password = newPasswordTF.text
newUser.email = emailTF.text
newUser["phoneNumber"] = phoneNumberTF.text
newUser.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if let error = error {
spinner.startAnimating()
self.alert("Opps", textMessage: (error.localizedDescription))
} else {
spinner.startAnimating()
self.alert("Congratualtion!", textMessage: "Success, your account has been created.")
self.performSegueWithIdentifier("showMessages", sender: self)
}
}
} else {
alert("Hmm...", textMessage: "If you want an account, please fill in the blanks.")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
self.navigationController!.navigationBar.hidden = false
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
profilePictureIV.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
func alert(textTitle: String, textMessage: String) {
let alertController = UIAlertController(title: textTitle, message: textMessage, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
If i play the self.performSegueWithIdentifier("showMessages", sender: self) line anywhere else then when i run the program and press the signup button it will directly go to in the messages view controller without any signup required.
as Paulw11 said , Try to remove alert message :-
if let error = error {
spinner.startAnimating()
self.alert("Opps", textMessage: (error.localizedDescription))
} else {
spinner.startAnimating()
self.performSegueWithIdentifier("showMessages", sender: self)
}
or You can call the handler in your code.
if let error = error {
spinner.startAnimating()
self.alert("Opps", textMessage: (error.localizedDescription))
} else {
spinner.startAnimating()
var alert = UIAlertController(title: "Welcome", message: "Login", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title:"OK", style: .Default, handler: { action in self.performSegueWithIdentifier("showMessages", sender: self) }
}
You can not pass self as a argument in side the block.
so create a method to call a segue
#IBAction func signUpButton(sender: AnyObject) {
let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
if firstNameTF.text != "" && lastNameTF.text != "" && newUsernameTF.text != "" && newPasswordTF.text != "" && emailTF.text != "" && phoneNumberTF.text != "" {
let newUser = PFUser()
if let profilePictureImage = profilePictureIV?.image {
let profilePicture = UIImageJPEGRepresentation(profilePictureImage, 1)!
let profilePictureImageFile = PFFile(data: profilePicture)
newUser["profilePicture"] = profilePictureImageFile
}
newUser["firstName"] = firstNameTF.text
newUser["lastName"] = lastNameTF.text
newUser.username = newUsernameTF.text
newUser.password = newPasswordTF.text
newUser.email = emailTF.text
newUser["phoneNumber"] = phoneNumberTF.text
newUser.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if let error = error {
spinner.startAnimating()
self.alert("Opps", textMessage: (error.localizedDescription))
} else {
spinner.startAnimating()
self.alert("Congratualtion!", textMessage: "Success, your account has been created.")
callSegue()
}
}
} else {
alert("Hmm...", textMessage: "If you want an account, please fill in the blanks.")
}
}
func callSegue()
{
self.performSegueWithIdentifier("showMessages", sender: self)
}

Resources