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?.
Related
Before I start, I would just like to pre-warn that my code is most likely not correct due to me being a beginner at coding with Swift.
I am creating an app for a university project, it is the first large app that I have created and I haven't been coding for very long.
I am having a problem when trying to upload an image whilst creating an account with firebase, I have had the code working previously but I was writing to the database with 'childByAutoId()' which was working fine, however I realised that I needed to be writing to the database and saving it by the users ID instead. After I changed 'childByAutoId()' to 'child(uid)' which is my prefixed variable for the users ID it stopped uploading the images and I can't figure out why. I have tried to go back to when it was working with childByAutoId() but now that isn't working either.
My code:
import UIKit
import Firebase
import FirebaseStorage
class RegisterViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var profileImage: UIImageView!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var dobField: UITextField!
#IBOutlet weak var selectImageButton: UIButton!
var imageFileName = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
let datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.date
datePicker.addTarget(self, action: #selector(RegisterViewController.datePickerValueChanged(sender:)), for: UIControlEvents.valueChanged)
dobField.inputView = datePicker
self.profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2;
self.profileImage.clipsToBounds = true;
}
#objc func datePickerValueChanged(sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.medium
formatter.timeStyle = DateFormatter.Style.none
dobField.text = formatter.string(from: sender.date)
}
#IBAction func selectImageTapped(_ sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
func uploadImage(image: UIImage) {
let randomName = randomStringWithLength(length: 10)
let imageData = UIImageJPEGRepresentation(image, 1.0)
let uploadRef = Storage.storage().reference().child("images/profimg/\(randomName).jpg")
let uploadTask = uploadRef.putData(imageData!, metadata: nil) { metadata,
error in
if error == nil {
//success
print("success")
self.imageFileName = "\(randomName as String).jpg"
} else {
//error
print("error uploading image")
}
}
}
func randomStringWithLength(length: Int) -> NSString {
let characters: NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString: NSMutableString = NSMutableString(capacity: length)
for i in 0..<length {
var len = UInt32(characters.length)
var rand = arc4random_uniform(len)
randomString.appendFormat("%C", characters.character(at: Int(rand)))
}
return randomString
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// will run if the user hits cancel
picker.dismiss(animated: true, completion: nil)
}
#objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// will run when the user finishes picking an image from the library
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.profileImage.image = pickedImage
self.selectImageButton.isEnabled = false
self.selectImageButton.isHidden = true
uploadImage(image: pickedImage)
picker.dismiss(animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func registerTapped(_ sender: UIButton) {
let username = usernameField.text
let email = emailField.text
let password = passwordField.text
let dob = dobField.text
Auth.auth().createUser(withEmail: email!, password: password!) { (user, error) in
if error != nil {
//error creating account
let alert = UIAlertController(title: "Error", message: "An error occurred when creating your account, please try again.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}else {
//account created
if (self.imageFileName != "") {
if let uid = Auth.auth().currentUser?.uid {
let regObject: Dictionary<String, Any> = [
"uid" : uid,
"username" : username,
"dateofbirth" : dob,
"profimage" : self.imageFileName
]
Database.database().reference().child("posts").child(uid).setValue(regObject)
let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoggedInVC")
self.present(vc!, animated: true, completion: nil)
}else {
//image hasnt finished uploading
let alert = UIAlertController(title: "Please wait", message: "Your image has not finished uploading yet, please wait...", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
//let alert = UIAlertController(title: "Success!", message: "Account has been created...", preferredStyle: .alert)
//alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
//self.present(alert, animated: true, completion: nil)
}
}
}
/*
// 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.
}
*/
}
If any of you can point me in the right direction or be able to show me where I have gone wrong within my code that would be great. I am not expected a direct solution to my problem so anything will help.
Thank you!
To upload img on firebase storage
func uploadImagePic(img1 :UIImage){
var data = NSData()
data = UIImageJPEGRepresentation(img1!, 0.8)! as NSData
// set upload path
let filePath = "\(userid)" // path where you wanted to store img in storage
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"
self.storageRef = FIRStorage.storage().reference()
self.storageRef.child(filePath).put(data as Data, metadata: metaData){(metaData,error) in
if let error = error {
print(error.localizedDescription)
return
}else{
//store downloadURL
let downloadURL = metaData!.downloadURL()!.absoluteString
}
}
}
In order to get the download url from the uploaded file, based on the answer, downloadURL from metaData is now deprecated, so this is the proper way:
storageRef.downloadURL(completion: { (url: URL?, error: Error?) in
print(url?.absoluteString) // <- Your url
})
You should get the download url from the reference that you just created, where you can find the downloadURL with a completion handler.
This is an updated Swift 5 answer:
func uploadImagePic(image: UIImage, name: String, filePath: String) {
guard let imageData: Data = image.jpegData(compressionQuality: 0.1) else {
return
}
let metaDataConfig = StorageMetadata()
metaDataConfig.contentType = "image/jpg"
let storageRef = Storage.storage().reference(withPath: filePath)
storageRef.putData(imageData, metadata: metaDataConfig){ (metaData, error) in
if let error = error {
print(error.localizedDescription)
return
}
storageRef.downloadURL(completion: { (url: URL?, error: Error?) in
print(url?.absoluteString) // <- Download URL
})
}
}
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.
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"
}
}
}
}
}
I am making a face detection app. I have written some code for detection but I am getting an error. Kindly suggest me an alternate solution.
Here is the code, and the error is at line number 3.
import UIKit
import CoreImage
class ViewController: UIViewController ,UIAlertViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet var imageView: UIImageView!
#IBAction func Moodify(_ sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
picker.sourceType = .camera
self.present(picker, animated: true, completion: { _ in })
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [AnyHashable: Any]) {
let chosenImage = info[UIImagePickerControllerEditedImage]
self.imageView!.image = chosenImage as? UIImage
picker.dismiss(animated: true, completion: { _ in })
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: { _ in })
}
}
func detect() {
guard let personciImage = CIImage(image: personPic.image!) else {
return
}
let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: accuracy)
let faces = faceDetector.featuresInImage(personciImage)
for face in faces as! [CIFaceFeature] {
print("Found bounds are \(face.bounds)")
let faceBox = UIView(frame: face.bounds)
faceBox.layer.borderWidth = 3
faceBox.layer.borderColor = UIColor.redColor().CGColor
faceBox.backgroundColor = UIColor.clearColor()
personPic.addSubview(faceBox)
if face.hasLeftEyePosition {
print("Left eye bounds are \(face.leftEyePosition)")
}
if face.hasRightEyePosition {
print("Right eye bounds are \(face.rightEyePosition)")
}
}
}
override func viewDidLoad() {
let alert = UIAlertController(title: "Error", message: "Device has no camera", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
/* if !UIImagePickerController.isSourceTypeAvailable(.camera) {
let myAlertView = UIAlertView (title: "Error", message: "Device has no camera", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "")
myAlertView.show()
} */
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You need to declare it and connect to a UIImageView in storyboard.
#IBOutlet weak var personPic: UIImageView!
This is basic of programming. How can you use something that you haven't declared, right? Ok good luck in your project.
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)
}