I'm using PFSignUpViewControllerDelegate and I want to perform a segue after user signup to setup their profile... But nothing works! Where should I put this code?
self.performSegueWithIdentifier("setupCliente", sender: self)
My Code:
import UIKit
import Parse
import ParseUI
import Bolts
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit
import CoreLocation
struct localizacaoActualizada {
static var rua = ""
static var localidade = ""
static var codigopostal = ""
static var giropostal = ""
static var country = ""
}
class ViewController: UIViewController, ENSideMenuDelegate, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate, CLLocationManagerDelegate {
var logInViewController: PFLogInViewController! = PFLogInViewController()
var signUpViewController: PFSignUpViewController! = PFSignUpViewController()
var localidadeActual = ""
#IBOutlet weak var userLogedIn: UILabel!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.sideMenuController()?.sideMenu?.delegate = self
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
// Se ta loggado
var user = PFUser.currentUser()
if (user?.username != nil) {
// self.performSegueWithIdentifier("aposLogin", sender: self)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
var user = PFUser.currentUser()
self.userLogedIn.text = user?.username
if (user?.username == nil) {
self.logInViewController.fields = ( PFLogInFields.UsernameAndPassword | PFLogInFields.LogInButton | PFLogInFields.SignUpButton | PFLogInFields.PasswordForgotten | PFLogInFields.DismissButton )
//PFLogInFields.Facebook
var logInLogoTitle = UILabel()
logInLogoTitle.text = "ParaFora"
var SignUpLogoTitle = UILabel()
SignUpLogoTitle.text = "ParaFora"
//self.logInViewController.facebookPermissions = [ "friends_about_me" ]
self.logInViewController.logInView!.logo = logInLogoTitle
self.logInViewController.delegate = self
self.signUpViewController.signUpView!.logo = SignUpLogoTitle
self.signUpViewController.delegate = self
self.logInViewController.signUpController = self.signUpViewController
}
else {
//Tentativa 1
//self.locationManager.stopUpdatingLocation()
var user = PFUser.currentUser()
user?["localidade"] = localidadeActual
user?.saveInBackground()
//tentativa 2
//var user = PFUser.currentUser()
//var idUser = user?["objectId"] as! String
// println("O id do utilizador actual:" + idUser)
// var query = PFQuery(className:"User")
// query.getObjectInBackgroundWithId(idUser) {
// (User: PFObject?, error: NSError?) -> Void in
// if error != nil {
// println(error)
// } else if let User = User {
// println("Tentativa de escrever" + self.localidadeActual + "no servidor")
// User["localidade"] = self.localidadeActual
// User.saveInBackground()
// println("done?")
// }
// }
//
// self.performSegueWithIdentifier("aposLogin", sender: self)
}
}
//Localizacao
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
if (error != nil)
{
println("Error: " + error.localizedDescription)
return
}
if placemarks.count > 0
{
let pm = placemarks[0] as! CLPlacemark
self.displayLocationInfo(pm)
}
else
{
println("Error with the data.")
}
})
}
func displayLocationInfo(placemark: CLPlacemark)
{
locationManager.stopUpdatingLocation()
//self.locationManager.stopUpdatingLocation()
println(placemark.locality)
println(placemark.postalCode)
println(placemark.administrativeArea)
println(placemark.country)
println(placemark.location)
println(placemark.administrativeArea)
println(placemark.subAdministrativeArea)
// println(placemark.addressDictionary)
// println(placemark.areasOfInterest)
localidadeActual = placemark.locality
localizacaoActualizada.rua = placemark.name
localizacaoActualizada.localidade = placemark.locality
//Guarda o codigo postal na estrutura
if count(placemark.postalCode) > 4{
localizacaoActualizada.codigopostal = placemark.postalCode.substringWithRange(Range<String.Index>(start: advance(placemark.postalCode.startIndex, 0), end: advance(placemark.postalCode.endIndex, -3)))
localizacaoActualizada.giropostal = placemark.postalCode.substringWithRange(Range<String.Index>(start: advance(placemark.postalCode.startIndex, 4), end: advance(placemark.postalCode.endIndex, 0)))
}
else {
localizacaoActualizada.codigopostal = placemark.postalCode
}
// Obtem a localidade no serv
var user = PFUser.currentUser()
println(user?["localidade"])
//fim obter localidade
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
println("Error: " + error.localizedDescription)
}
//fim local
// MARK: Parse Login
func logInViewController(logInController: PFLogInViewController, shouldBeginLogInWithUsername username: String, password: String) -> Bool {
if (!username.isEmpty || !password.isEmpty) {
return true
}else {
return false
}
}
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
self.dismissViewControllerAnimated(true, completion: nil)
self.performSegueWithIdentifier("aposLogin", sender: self)
}
func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) {
println("Failed to login...")
}
func logInViewControllerDidCancelLogIn(logInController: PFLogInViewController) {
}
// MARK: Parse Signup
func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func signUpViewController(signUpController: PFSignUpViewController, didFailToSignUpWithError error: NSError?) {
println("FAiled to sign up...")
}
func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) {
println("User dismissed sign up.")
}
// MARK: Actions
#IBAction func simpleAction(sender: AnyObject) {
self.presentViewController(self.logInViewController, animated: true, completion: nil)
}
#IBAction func logoutAction(sender: AnyObject) {
PFUser.logOut()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func toggleSideMenu(sender: AnyObject) {
toggleSideMenuView()
}
// MARK: - ENSideMenu Delegate
func sideMenuWillOpen() {
println("sideMenuWillOpen")
}
func sideMenuWillClose() {
println("sideMenuWillClose")
}
func sideMenuShouldOpenSideMenu() -> Bool {
println("sideMenuShouldOpenSideMenu")
return true
}
}
self.performSegueWithIdentifier("setupCliente", sender: self)
There is nothing immediately wrong with this code, and you should be able to call it from where you want it. However, I suspect that you have not set up your segue correctly in your Storyboard (I'm assuming you are using Storyboards). To do this, you need to setup a manual segue.
You have to drag a segue from the yellow button on top to the next view controller, and from there choose a manual segue (ie: manual push). Then click on that segue and name it with your identifier - setupCliente. Only then will the view controller recognize the segue and be able to use it to reach the next view controller.
Also make sure that each view has its correct view controller assigned to it.
Related
I have a counter in my game that adds a score by 1, and I want a rewarded video on my game over screen that can boost the player score by 100 but I'm not sure how to execute the function when the ad ends. Here is my code:
// FirstViewController.swift
import UIKit
import Firebase
import AVFoundation
import StoreKit
import GameKit
import Appodeal
class Page1: UIViewController, AVAudioPlayerDelegate, GADInterstitialDelegate, UIAlertViewDelegate, GKGameCenterControllerDelegate, AppodealInterstitialDelegate {
let ncObserver = NotificationCenter.default
let PlayAgainObserver = NotificationCenter.default
let AddScoreObserver = NotificationCenter.default
var player = AVAudioPlayer()
/* Variables */
var gcEnabled = Bool() // Check if the user has Game Center enabled
var gcDefaultLeaderBoard = String() // Check the default leaderboardID
var score = 0
let LEADERBOARD_ID = "ScoreID"
var interstitial: GADInterstitial!
var counter: Int = 0
var counter2: Int = 0
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var pageControl: UIPageControl!
#IBOutlet weak var placementField: UITextField!
// #IBOutlet weak var testpulse: UIButton!
let notification = NotificationCenter.default
let notification2 = NotificationCenter.default
override func viewDidLoad() {
super.viewDidLoad()
authenticateLocalPlayer()
Appodeal.setInterstitialDelegate(self)
ncObserver.addObserver(self, selector: #selector(self.StopSoundsfunc), name: Notification.Name("StopSounds"), object:nil)
PlayAgainObserver.addObserver(self, selector: #selector(self.PlayAgainfunc), name: Notification.Name("PlayAgain"), object:nil)
AddScoreObserver.addObserver(self, selector: #selector(self.AddScorefunc), name: Notification.Name("AddScore"), object:nil)
interstitial = GADInterstitial(adUnitID: "ca-app-pub-6626761084276338/5899386416")
let request = GADRequest()
interstitial.load(request)
}
#IBAction func playAgain(_ sender: Any) {
if counter % 15 == 0 {
if interstitial.isReady {
interstitial.present(fromRootViewController: self)
interstitial = CreateAd()
} else {
print("Ad wasn't ready")
}
}
counter += 1
}
#objc func PlayAgainfunc(_ sender: Any) {
if counter % 15 == 0 {
if interstitial.isReady {
interstitial.present(fromRootViewController: self)
interstitial = CreateAd()
} else {
print("Ad wasn't ready")
}
}
counter += 1
}
#IBAction func ShowAds(_ sender: Any) {
// notification.post(name: Notification.Name("PlayAgain"), object: nil)
Appodeal.showAd(AppodealShowStyle.interstitial, rootViewController: self)
}
#IBAction func AddScore(_ sender: Any) {
notification.post(name: Notification.Name("AddScore"), object: nil)
}
// MARK: - OPEN GAME CENTER LEADERBOARD
#IBAction func checkGCLeaderboard(_ sender: AnyObject) {
let gcVC = GKGameCenterViewController()
gcVC.gameCenterDelegate = self
gcVC.viewState = .leaderboards
gcVC.leaderboardIdentifier = LEADERBOARD_ID
present(gcVC, animated: true, completion: nil)
}
// MARK: - ADD 10 POINTS TO THE SCORE AND SUBMIT THE UPDATED SCORE TO GAME CENTER
#objc func AddScorefunc(_ sender: AnyObject) {
// Add 1 point to current score
score += 1
// Submit score to GC leaderboard
let bestScoreInt = GKScore(leaderboardIdentifier: LEADERBOARD_ID)
bestScoreInt.value = Int64(score)
GKScore.report([bestScoreInt]) { (error) in
if error != nil {
print(error!.localizedDescription)
} else {
print("Best Score submitted to your Leaderboard!")
}
}
}
// MARK: - AUTHENTICATE LOCAL PLAYER
func authenticateLocalPlayer() {
let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = {(ViewController, error) -> Void in
if((ViewController) != nil) {
// 1. Show login if player is not logged in
self.present(ViewController!, animated: true, completion: nil)
} else if (localPlayer.isAuthenticated) {
// 2. Player is already authenticated & logged in, load game center
self.gcEnabled = true
// Get the default leaderboard ID
localPlayer.loadDefaultLeaderboardIdentifier(completionHandler: { (leaderboardIdentifer, error) in
if error != nil { print(error)
} else { self.gcDefaultLeaderBoard = leaderboardIdentifer! }
})
} else {
// 3. Game center is not enabled on the users device
self.gcEnabled = false
print("Local player could not be authenticated!")
print(error!)
}
}
}
func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismiss(animated: true, completion: nil)
}
}
func CreateAd() -> GADInterstitial {
let interstitial = GADInterstitial(adUnitID: "ca-app-pub-6626761084276338/5899386416")
interstitial.load(GADRequest())
return interstitial
}
func interstitialDidFailToLoadAd(){
NSLog("Interstitial failed to load")
}
func interstitialDidReceiveAd(_ interstitial: GADInterstitial) {
print("Interstitial adapter class name: \(String(describing: interstitial.adNetworkClassName))")
}
#IBAction func RewardedVideo(_ sender: Any) {
Appodeal.showAd(AppodealShowStyle.rewardedVideo, rootViewController: self)
}
In my "AddScorefunc" I have a counter that increases the score by 1. I want to create a similar function that increases the score by 100 but only if the rewarded video requirements are met.
If we look into the SDK integration guide of AppoDeal, they have provided delegates for all kind of ads you show through their sdk. For your case of showing a rewarded video, the delegate is AppodealRewardedVideoDelegate and here is how you can use it to get the callback and add score.
extension Page1: AppodealRewardedVideoDelegate {
func rewardedVideoDidLoadAd(){
NSLog("video ad was loaded")
}
func rewardedVideoDidFailToLoadAd(){
NSLog("video ad failed to load")
}
func rewardedVideoDidPresent(){
NSLog("video ad was presented");
}
func rewardedVideoWillDismiss(){
NSLog("video ad was closed");
}
func rewardedVideoDidFinish(_ rewardAmount: UInt, name rewardName: String!){
NSLog("video ad was fully watched");
// Add score here i.e, score += 100
}
}
In viewDidLoad of Page1, set the delegate method like this,
override func viewDidLoad() {
super.viewDidLoad()
// set delegate
Appodeal.setRewardedVideoDelegate(self)
}
I'm having quite some troubles implementing Facebook login in my iOS , everything works fine if the user is not already logged in, the application fetches correctly the data from Facebook and pass them to the next ViewController , instead if is already logged in it should automatically segue to a recap page that shows user's info but i can't make it happen, currently I'm using this method :
override func viewDidLoad() {
super.viewDidLoad()
LoginButton.delegate = self
if (FBSDKAccessToken.currentAccessToken() != nil) {
self.performSegueWithIdentifier("Login", sender: self)
}
}
but in the console i get :
Facebook_Login.LoginViewController: 0x7fc04a519ca0 on Facebook_Login.ViewController: 0x7fc04a41c1e0 whose view is not in the window hierarchy!
i've also tried using the viewdidAppear method, but it segues to the recap page without updating the variables so i get an empty page
here' the complete code:
View Controller 1
import UIKit
import FBSDKLoginKit
class ViewController: UIViewController,FBSDKLoginButtonDelegate {
var nome1:String = ""
var cognome1:String = ""
var email1:String = ""
var compleanno:String = ""
var città:String = ""
var genere:String = ""
var immagine_url:String = ""
#IBOutlet weak var LoginButton: FBSDKLoginButton!
#IBAction func LoginAction(sender: AnyObject) {
LoginButton.delegate = self
LoginButton.readPermissions = ["email"]
}
func FetchInfo(){
print("scarico le informazioni...")
let parametri = ["fields":"email, first_name, last_name, birthday, hometown, gender, picture.type(large)"]
FBSDKGraphRequest(graphPath: "me", parameters: parametri).startWithCompletionHandler{(connection,result,error) -> Void in
if (error != nil){
print ("errore")
return
}
else {
if let email = result["email"] as? String {
print(email)
self.email1 = email
}
if let nome = result["first_name"] as? String {
print(nome)
self.nome1 = nome
}
if let cognome = result["last_name"] as? String {
print(cognome)
self.cognome1 = cognome
}
if let compleanno = result["birthday"] as? String{
print(compleanno)
}
if let città = result["hometown"] as? String{
print(città)
}
if var genere = result["gender"] as? String{
if (genere == "male"){
genere = "maschio"
}
else {
genere = "femmina"
}
print(genere)
}
}
if let picture = result["picture"] as? NSDictionary, data = picture["data"] as? NSDictionary, url = data["url"] as? String{
self.immagine_url = url
print(self.immagine_url)
}
}
return
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!){
if (result.isCancelled == true){
print("cancellato")
}
else {
print("login effettuato")
FetchInfo()
self.performSegueWithIdentifier("Login", sender: self)
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!){
}
func loginButtonWillLogin(loginButton: FBSDKLoginButton!) -> Bool{
return true
}
#IBAction func returned(segue:UIStoryboardSegue){
}
override func viewDidLoad() {
super.viewDidLoad()
LoginButton.delegate = self
}
override func viewDidAppear(animated: Bool) {
if (FBSDKAccessToken.currentAccessToken() != nil) {
FetchInfo()
if(nome1 == ""){
}
else {
self.performSegueWithIdentifier("Login", sender: self)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destinazione:LoginViewController = segue.destinationViewController
as! LoginViewController
destinazione.temp_nome = nome1
destinazione.temp_cognome = cognome1
destinazione.temp_email = email1
destinazione.img_profile_url = immagine_url
}
}
ViewController 2:
import UIKit
import FBSDKLoginKit
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {
var temp_nome = ""
var temp_cognome = ""
var temp_email = ""
var img_profile_url:String = ""
#IBOutlet weak var Nome_Utente: UILabel!
#IBOutlet weak var email: UILabel!
#IBOutlet weak var Immagine_Utente: UIImageView!
#IBOutlet weak var Login_button: FBSDKLoginButton!
#IBAction func Login_button_Action(sender: AnyObject) {
Login_button.delegate = self
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!){
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!){
self.performSegueWithIdentifier("Back", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
Nome_Utente.text = "\(temp_nome)" + " " + "\(temp_cognome)"
email.text = "\(temp_email)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
First of all, avoid to reset your LoginButton.delegate in the LoginAction() function.
If the user is already logged in, to avoid an useless call to the Facebook Graph API (if you do not necessarily need to update his informations), you can store your user informations in CoreData or in a NSUserDefault.
If you never used it you can use the CDHelper lib (CoreDataHelper) which will allow you to use it without difficulties.
Hope I was helpful, if not, do not hesitate to give us a feedback.
Btw, in your viewDidAppear(animated: Bool) function, you have to call super.viewDidAppear(animated) !
I am using parse's provided login code for their latest ParseUI. I am confused why I am getting this error every single time I use self.logInViewController and self.signUpViewController, the error being:
Ambiguous reference to member 'logInViewController' and 'signUpViewController'
Here is my code:
import Parse
import ParseUI
import UIKit
class ViewController: UIViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate {
#IBAction func simpleAction(sender: AnyObject) {
self.presentViewController(self.logInViewController, animated: true, completion: nil)
}
#IBAction func customAction(sender: AnyObject) {
self.performSegueWithIdentifier("custom", sender: self)
}
#IBAction func logoutAction(sender: AnyObject) {
PFUser.logOut()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if (PFUser.currentUser() == nil) {
self.logInViewController.fields = PFLogInFields.UsernameAndPassword | PFLogInFields.LogInButton | PFLogInFields.SignUpButton | PFLogInFields.PasswordForgotten | PFLogInFields.DismissButton
var logInLogoTitle = UILabel()
logInLogoTitle.text = "Parse"
self.logInViewController.logInView.logo = logInLogoTitle
self.logInViewController.delegate = self
var SignUpLogoTitle = UILabel()
SignUpLogoTitle.text = "Parse"
self.signUpViewController.signUpView.logo = SignUpLogoTitle
self.signUpViewController.delegate = self
self.logInViewController.signUpController = self.signUpViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func logInViewController(logInController: PFLogInViewController!, shouldBeginLogInWithUsername username: String!, password: String!) -> Bool {
if (!username.isEmpty || !password.isEmpty) {
return true
}else {
return false
}
}
func logInViewController(logInController: PFLogInViewController!, didLogInUser user: PFUser!) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func logInViewController(logInController: PFLogInViewController!, didFailToLogInWithError error: NSError!) {
print("Failed to login...")
}
func logInViewControllerDidCancelLogIn(logInController: PFLogInViewController!) {
}
func signUpViewController(signUpController: PFSignUpViewController!, didSignUpUser user: PFUser!) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func signUpViewController(signUpController: PFSignUpViewController!, didFailToSignUpWithError error: NSError!) {
print("FAiled to sign up...")
}
func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController!) {
print("User dismissed sign up.")
}
}
logInViewController and signUpViewController are both undefined.
You need to define them with:
let logInViewController = PFLogInViewController()
let signUpViewController = PFSignUpViewController()
It does not seem like my data is passed to the new view controller.
Indeed, it only works in the (first) view controller once logged in.
I believe there are a few mistakes in my work.
Please tell me where I'm wrong, I am a beginner so please be precise and efficient. Thanks a lot.
class ViewController: UIViewController, FBSDKLoginButtonDelegate
{
override func viewDidLoad()
{
super.viewDidLoad()
if FBSDKAccessToken.currentAccessToken() != nil {
//user already has access token
self.logUserData()
} else {
loginButton.readPermissions = ["public_profile", "email", "user_friends"]
loginButton.delegate = self
self.Photo.image = UIImage(named: "Why subtle bckd image1")
self.Photo2.image = UIImage(named: "Un combo unique pict")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: PR/VAR
var firstName: String!
var lastName: String!
var email: String!
#IBOutlet var loginButton: FBSDKLoginButton!
#IBAction func loginButtonsend(sender: UIButton) {
sender.setTitle("firstName", forState: UIControlState.Normal)
sender.setTitle("lastName", forState: UIControlState.Normal)
sender.setTitle("email", forState: UIControlState.Normal)
}
#IBOutlet var Photo: UIImageView!
#IBOutlet var Photo2: UIImageView!
// MARK: FACEBOOK LOGIN
override func viewWillAppear(animated: Bool) {
self.logUserData()
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)
{ if error == nil {
let fbAccessToken = FBSDKAccessToken.currentAccessToken().tokenString
println("Logged in")
} else { println(error.localizedDescription) } }
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!)
{
println("User logged out.")
}
func logUserData()
{
let graphRequest = FBSDKGraphRequest(graphPath: "me?fields=id,email,first_name,last_name", parameters: ["fields": "first_name,email,last_name"])
graphRequest.startWithCompletionHandler { (connection, result, error) -> Void in
if error != nil
{
// Process error
println(error)
}
else
{
println(result.grantedPermissions)
println("fetched user = \(result)")
var firstName = result.valueForKey("first_name")
println("firstName = \(firstName)")
var lastName = result.valueForKey("last_name")
println("lastName is = \(lastName)")
var email = result.valueForKey("email")
println("email is = \(email)")
self.performSegueWithIdentifier("showNew", sender: self)
}
}
}
// SEGUE:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "showNew") {
if let destinationVC = segue.destinationViewController as? NewViewController {
destinationVC.firstName = firstName
destinationVC.lastName = lastName
destinationVC.email = email
}
}
}
}
And in my new view controller I have the following:
class NewViewController: UIViewController {
var firstName: String!
var lastName: String!
var email: String!
#IBOutlet var firstNameLabel: UILabel!
#IBOutlet var lastNameLabel: UILabel!
#IBOutlet var emailLabel: UILabel!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if (firstName != nil) {
firstNameLabel.text = firstName
}
if (lastName != nil) {
lastNameLabel.text = lastName
}
if (email != nil) {
emailLabel.text = email
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func logoutButtonTapped(sender: AnyObject) {
let loginManager = FBSDKLoginManager ()
loginManager.logOut()
let loginPage = self.storyboard?.instantiateViewControllerWithIdentifier("ViewController") as ViewController
//?
let loginPageNav = UINavigationController (rootViewController: loginPage)
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
appDelegate.window?.rootViewController = loginPageNav
}
/*
// 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.
}
*/
}
It seems like you're never setting the variables from your ViewController, but instead are creating three which have the same name as the ones you should be using on logUserData. Just change to:
println(result.grantedPermissions)
println("fetched user = \(result)")
firstName = result.valueForKey("first_name")
println("firstName = \(firstName)")
lastName = result.valueForKey("last_name")
println("lastName is = \(lastName)")
email = result.valueForKey("email")
println("email is = \(email)")
I'm using performSegueWithIdentifier and everything is OK on all of them, but there is one that doesnt work at all.
I'm using Parse.com to signup a user and I want to perform a segue after they sigup, but I can't get it to work. I think the performSegue should be place at function signUpViewController
My code:
import UIKit
import Parse
import ParseUI
import Bolts
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit
import CoreLocation
struct localizacaoActualizada {
static var rua = ""
static var localidade = ""
static var codigopostal = ""
static var giropostal = ""
static var country = ""
}
class ViewController: UIViewController, ENSideMenuDelegate, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate, CLLocationManagerDelegate {
var logInViewController: PFLogInViewController! = PFLogInViewController()
var signUpViewController: PFSignUpViewController! = PFSignUpViewController()
var localidadeActual = ""
#IBOutlet weak var userLogedIn: UILabel!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.sideMenuController()?.sideMenu?.delegate = self
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
// Se ta loggado
var user = PFUser.currentUser()
if (user?.username != nil) {
// self.performSegueWithIdentifier("aposLogin", sender: self)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
var user = PFUser.currentUser()
self.userLogedIn.text = user?.username
if (user?.username == nil) {
self.logInViewController.fields = ( PFLogInFields.UsernameAndPassword | PFLogInFields.LogInButton | PFLogInFields.SignUpButton | PFLogInFields.PasswordForgotten | PFLogInFields.DismissButton )
//PFLogInFields.Facebook
var logInLogoTitle = UILabel()
logInLogoTitle.text = "ParaFora"
var SignUpLogoTitle = UILabel()
SignUpLogoTitle.text = "ParaFora"
//self.logInViewController.facebookPermissions = [ "friends_about_me" ]
self.logInViewController.logInView!.logo = logInLogoTitle
self.logInViewController.delegate = self
self.signUpViewController.signUpView!.logo = SignUpLogoTitle
self.signUpViewController.delegate = self
self.logInViewController.signUpController = self.signUpViewController
}
else {
//Tentativa 1
//self.locationManager.stopUpdatingLocation()
var user = PFUser.currentUser()
user?["localidade"] = localidadeActual
user?.saveInBackground()
//tentativa 2
//var user = PFUser.currentUser()
//var idUser = user?["objectId"] as! String
// println("O id do utilizador actual:" + idUser)
// var query = PFQuery(className:"User")
// query.getObjectInBackgroundWithId(idUser) {
// (User: PFObject?, error: NSError?) -> Void in
// if error != nil {
// println(error)
// } else if let User = User {
// println("Tentativa de escrever" + self.localidadeActual + "no servidor")
// User["localidade"] = self.localidadeActual
// User.saveInBackground()
// println("done?")
// }
// }
//
// self.performSegueWithIdentifier("aposLogin", sender: self)
}
}
//Localizacao
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
if (error != nil)
{
println("Error: " + error.localizedDescription)
return
}
if placemarks.count > 0
{
let pm = placemarks[0] as! CLPlacemark
self.displayLocationInfo(pm)
}
else
{
println("Error with the data.")
}
})
}
func displayLocationInfo(placemark: CLPlacemark)
{
locationManager.stopUpdatingLocation()
//self.locationManager.stopUpdatingLocation()
println(placemark.locality)
println(placemark.postalCode)
println(placemark.administrativeArea)
println(placemark.country)
println(placemark.location)
println(placemark.administrativeArea)
println(placemark.subAdministrativeArea)
// println(placemark.addressDictionary)
// println(placemark.areasOfInterest)
localidadeActual = placemark.locality
localizacaoActualizada.rua = placemark.name
localizacaoActualizada.localidade = placemark.locality
//Guarda o codigo postal na estrutura
if count(placemark.postalCode) > 4{
localizacaoActualizada.codigopostal = placemark.postalCode.substringWithRange(Range<String.Index>(start: advance(placemark.postalCode.startIndex, 0), end: advance(placemark.postalCode.endIndex, -3)))
localizacaoActualizada.giropostal = placemark.postalCode.substringWithRange(Range<String.Index>(start: advance(placemark.postalCode.startIndex, 4), end: advance(placemark.postalCode.endIndex, 0)))
}
else {
localizacaoActualizada.codigopostal = placemark.postalCode
}
// Obtem a localidade no serv
var user = PFUser.currentUser()
println(user?["localidade"])
//fim obter localidade
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
println("Error: " + error.localizedDescription)
}
//fim local
// MARK: Parse Login
func logInViewController(logInController: PFLogInViewController, shouldBeginLogInWithUsername username: String, password: String) -> Bool {
if (!username.isEmpty || !password.isEmpty) {
return true
}else {
return false
}
}
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
self.dismissViewControllerAnimated(true, completion: nil)
self.performSegueWithIdentifier("aposLogin", sender: self)
}
func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) {
println("Failed to login...")
}
func logInViewControllerDidCancelLogIn(logInController: PFLogInViewController) {
}
// MARK: Parse Signup
func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) {
self.dismissViewControllerAnimated(true, completion: nil)
self.performSegueWithIdentifier("setupCliente", sender:self)
}
func signUpViewController(signUpController: PFSignUpViewController, didFailToSignUpWithError error: NSError?) {
println("FAiled to sign up...")
}
func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) {
println("User dismissed sign up.")
}
// MARK: Actions
#IBAction func simpleAction(sender: AnyObject) {
self.presentViewController(self.logInViewController, animated: true, completion: nil)
}
#IBAction func logoutAction(sender: AnyObject) {
PFUser.logOut()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func toggleSideMenu(sender: AnyObject) {
toggleSideMenuView()
}
// MARK: - ENSideMenu Delegate
func sideMenuWillOpen() {
println("sideMenuWillOpen")
}
func sideMenuWillClose() {
println("sideMenuWillClose")
}
func sideMenuShouldOpenSideMenu() -> Bool {
println("sideMenuShouldOpenSideMenu")
return true
}
}
In your signUpViewController function you are dismissing the current view controller and then you are calling performSegueWithIdentifier with the sender as the view controller you just dismissed. Try removing the dismissViewControllerAnimated method call
I had the same problem. But I managed to solve it, although it is not a perfect solution.
What I did was to dismiss the PFSignUpViewController.
But before I did that I set a global variable, a bool called initialSignUp in my case to true. Once the controller was dismissed I checked in the PFLogInViewController's viewDidAppear() method if initialSignUp was true.
If this was the case I changed it back to false and then performed the segue.
This workaround works for me and I hope I could help you with your problem.
I think you need to set the delegate of the loginViewController's signupViewController. Something like this (sorry it's in swift, but you can propably work it out):
let loginViewController = LoginViewController()
loginViewController.delegate = self
loginViewController.signUpController?.delegate = self
and then, you can call the following methods to dismiss the view and perform the segue (or anything else).
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
self.dismissViewControllerAnimated(true, completion: nil)
self.performSegueWithIdentifier("segueID")
}
func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) -> Void {
self.dismissViewControllerAnimated(true, completion: nil)
self.performSegueWithIdentifier("segueID")
}
Hope this help. It worked for me.
Cheers,
Julien