Parse Login self.logInViewController ambiguous reference to member ' logInViewController' - ios

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()

Related

admob interstitial ad is never ready [duplicate]

This question already exists:
admob interstitial alway returns false
Closed 6 years ago.
i have this game and i created 3 funcions in my gameviewcontroller and here they are
func getInterstitialAd(){
interstitial = GADInterstitial(adUnitID: "ca-app-pub-1782852253088296/5018877964")
let requestInterstitial = GADRequest()
interstitial.load(requestInterstitial)
}
func showAd() {
if (interstitial.isReady == true){
interstitial.present(fromRootViewController: GameViewController())
}else{
print("ad wasn't ready")
interstitial = createAd()
}
}
func createAd() -> GADInterstitial{
let interstital = GADInterstitial(adUnitID: "ca-app-pub-1782852253088296/5018877964")
interstitial.load(GADRequest())
return interstital
}
and in one of my scene called StartMenu , i call those function
var viewController: GameViewController!
and then i call the functions
viewController.getInterstitialAd()
viewController.showAd()
but it always returns ad not ready , and false for interstitial.isReady,
but also the getInterstitial function is always called .
can someone help with that please
Create a new swift file AdMobDelegate :-
import UIKit
import GoogleMobileAds
class AdMobDelegate: NSObject, GADInterstitialDelegate {
var interstitialView: GADInterstitial!
func createAd() -> GADInterstitial {
interstitialView = GADInterstitial(adUnitID: "Your Key")
interstitialView.delegate = self
let request = GADRequest()
interstitialView.loadRequest(request)
return interstitialView
}
func showAd() {
if interstitialView != nil {
if (interstitialView.isReady == true){
interstitialView.present(fromRootViewController:currentVc)
} else {
print("ad wasn't ready")
interstitialView = createAd()
}
} else {
print("ad wasn't ready")
interstitialView = createAd()
}
}
func interstitialDidReceiveAd(ad: GADInterstitial!) {
print("Ad Received")
if ad.isReady {
interstitialView.present(fromRootViewController: currentVc)
}
}
func interstitialDidDismissScreen(ad: GADInterstitial!) {
print("Did Dismiss Screen")
}
func interstitialWillDismissScreen(ad: GADInterstitial!) {
print("Will Dismiss Screen")
}
func interstitialWillPresentScreen(ad: GADInterstitial!) {
print("Will present screen")
}
func interstitialWillLeaveApplication(ad: GADInterstitial!) {
print("Will leave application")
}
func interstitialDidFailToPresentScreen(ad: GADInterstitial!) {
print("Failed to present screen")
}
func interstitial(ad: GADInterstitial!, didFailToReceiveAdWithError error: GADRequestError!) {
print("\(ad) did fail to receive ad with error \(error)")
}
}
Now you can use the object of this delegate class in other files as follows :-
//Define admobdelegate as global variable
var admobDelegate = AdMobDelegate()
//Declare a global variable currentVc to hold reference to current view controller
var currentVc: UIViewController!
class abc1: UIViewController {
override func viewdidload() {
super.viewdidload()
currentVc = self
admobDelegate.showAd()
}
override func viewDidAppear() {
super.viewDidAppear()
currentVc = self
}
}
class abc2: UIViewController {
override func viewdidload() {
super.viewdidload()
currentVc = self
admobDelegate.showAd()
}
override func viewDidAppear() {
super.viewDidAppear()
currentVc = self
}
}
Code is in Swift 2.2. Write your equivalent code in swift 3 in case of syntax error.

Facebook Login for Swift with facebook iOS SDK 4.9.1

I got trouble with facebook iOS SDK 4.9.1 on integrating facebook login using swift. and main trouble is unable to find any guideline regarding it for swift.
http://www.brianjcoleman.com/tutorial-how-to-use-login-in-facebook-sdk-4-0-for-swift/
http://swiftdeveloperblog.com/facebook-sdk-ios-login-example-with-swift/
IOS Swift and Facebook SDK
I try to implement below but it doesn't work at all.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if (FBSDKAccessToken.currentAccessToken() != nil)
{
// User is already logged in, do work such as go to next view controller.
}
else
{
let loginView : FBSDKLoginButton = FBSDKLoginButton()
self.view.addSubview(loginView)
loginView.center = self.view.center
loginView.readPermissions = ["public_profile", "email", "user_friends"]
loginView.delegate = self
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is for viewcontroller :
import FBSDKLoginKit
class ViewController: UIViewController,FBSDKLoginButtonDelegate {
#IBOutlet weak var fbLoginView: FBSDKLoginButton!
override func viewDidLoad() {
super.viewDidLoad()
if(FBSDKAccessToken.currentAccessToken() == nil){
print("Not Logged ")
}
else{
print("Logged In")
}
fbLoginView.readPermissions = ["public_profile","email","user_birthday"]
fbLoginView.delegate = self
// 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.
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)
{
if error == nil
{
print("login complete")
let request = FBSDKGraphRequest(graphPath:"me", parameters:["fields":"name,gender,birthday,first_name,last_name,email"])
request.startWithCompletionHandler
{
(connection, result, error) in
if error != nil
{
print ("error \(error)")
}
else if let userData = result as? NSDictionary
{
var frstname = userData["first_name"] as? String
var lastname = userData["last_name"] as? String
var gender = userData["gender"] as? String
var birthday = userData["birthday"] as? String
var email = userData["email"] as? String
print(result)
}
}
}
else
{
print(error.localizedDescription)
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!)
{
print("user logged out")
}
}
In App Delegate override the following method as :
func application(application: UIApplication,openURL url: NSURL, sourceApplication: String?,annotation: AnyObject) -> Bool
{
return FBSDKApplicationDelegate.sharedInstance().application(application,openURL: url,sourceApplication: sourceApplication,annotation: annotation)
}
Swift 5+
In App Delegate override the following method as :
func application(application: UIApplication,openURL url: NSURL, sourceApplication: String?,annotation: AnyObject) -> Bool
{
return ApplicationDelegate.sharedInstance().application(application,openURL: url,sourceApplication: sourceApplication,annotation: annotation)
}

performSegueWithIdentifier not working after Signup with Parse

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

Can't perform a segue after signup using PFSignUpViewControllerDelegate

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.

Show Game Centre Leaderboard not working in swift

I am coding in swift and I am getting the following error message from my submit button. The leaderboard does not show up in the simulator, just gives me the error message below
<GKGameCenterViewController: 0x7a8d0800> on <Chinese_Quiz.OpeningViewController: 0x78688aa0> whose view is not in the window hierarchy!
Below is all the game centre code from my app.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Randomize()
Hide()
authenticateLocalPlayer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Submit(sender: AnyObject) {
saveHighscore(Score)
showLeaderboard()
}
func authenticateLocalPlayer(){
var localPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = {(viewController, error) -> Void in
if (viewController != nil) {
self.presentViewController(viewController, animated: true, completion: nil)
}
else {
println((GKLocalPlayer.localPlayer().authenticated))
}
}
}
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!)
{
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
func showLeaderboard() {
var vc = self.view?.window?.rootViewController
var gc = GKGameCenterViewController()
gc.gameCenterDelegate = self
vc?.presentViewController(gc, animated: true, completion: nil)
}
func saveHighscore(score:Int) {
//check if user is signed in
if GKLocalPlayer.localPlayer().authenticated {
var scoreReporter = GKScore(leaderboardIdentifier: "ChineseWeather") //leaderboard id here
scoreReporter.value = Int64(Score) //score variable here (same as above)
var scoreArray: [GKScore] = [scoreReporter]
GKScore.reportScores(scoreArray, withCompletionHandler: {(error : NSError!) -> Void in
if error != nil {
println("error")
}
})
}
}
Solved by turning this:
func showLeaderboard() {
var vc = self.view?.window?.rootViewController
var gc = GKGameCenterViewController()
gc.gameCenterDelegate = self
vc?.presentViewController(gc, animated: true, completion: nil)
}
Into this:
func showLeaderboard() {
var vc = self
var gc = GKGameCenterViewController()
var gameCenterDelegate: GKGameCenterControllerDelegate!
// Above text was replaced from gc.gameCenterDelegate = self
vc.presentViewController(gc, animated: true, completion: nil)
}
I don't know why, but it worked.

Resources