Facebook Login for Swift with facebook iOS SDK 4.9.1 - ios

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

Related

Changing ViewController if user is Facebook Logged in

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

Swift IOS Facebook Login Fast-App-Switch

Im a swift beginner and have already implemented FB login for IOS. I was wondering how to do it with Fast-App-Switching and staying on the App without moving to Facebook login form.
Heres my code for the ViewController.swift handling FB Login:
import UIKit
import Foundation
class FacebookLoginViewController : UIViewController, FBSDKLoginButtonDelegate {
let loginButton: FBSDKLoginButton = {
let button = FBSDKLoginButton()
button.readPermissions = ["public_profile","email","user_friends"]
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(loginButton)
loginButton.center = view.center
loginButton.delegate = self
if let token = FBSDKAccessToken.currentAccessToken() {
fetchProfile()
}
}
func fetchProfile() {
print("User Profile fetched")
redirectToHome()
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
print("User has successfully logged on.")
redirectToHome()
}
func redirectToHome() {
let storyboard:UIStoryboard = UIStoryboard(name:"Main", bundle: nil)
let homeFeed: UIViewController = storyboard.instantiateViewControllerWithIdentifier("homeFeed") as UIViewController
self.presentViewController(homeFeed, animated: true, completion: nil)
}
func loginButtonWillLogin(loginButton: FBSDKLoginButton!) -> Bool {
return true
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
print("User has logged out")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
As far as I knew and since I saw your question did further research, it is still not possible to skip the second screen. By second screen I mean a webpage where you must tap "log in" and it provides details about how the app will interact with Facebook. Even the app for this website takes you there when logging in with Facebook. If it this changes or I am mistaken I will update this post. Since I just joined the site I cannot post pictures yet:) but I hope we are talking about the same thing.

Doesn't call Facebook loginButton didCompleteWithResult

I followed the tutorial here to integrate Facebook login on my application. I can login successfully with that button, but it doesn't call my method didCompleteWithResult upon login to fetch user details. This is my code.
import UIKit
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {
#IBOutlet weak var loginBtn: FBSDKLoginButton!
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.
}
func configureFacebook()
{
loginBtn.readPermissions = ["public_profile", "email", "user_friends"];
loginBtn.delegate = self
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!){
FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields":"first_name, last_name, picture.type(large)"]).startWithCompletionHandler { (connection, result, error) -> Void in
let strFirstName: String = (result.objectForKey("first_name") as? String)!
let strLastName: String = (result.objectForKey("last_name") as? String)!
let strPictureURL: String = (result.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as? String)!
print("Welcome, \(strFirstName) \(strLastName)")
//self.profilePic.image = UIImage(data: NSData(contentsOfURL: NSURL(string: strPictureURL)!)!)
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!)
{
}
}
Option-1
I dont know where you add this method in here I submit answer in dynamically , customize your self..
override func viewDidLoad() {
super.viewDidLoad()
configureFacebook() // if you want here add here or else if you want to load the facebook details in Button action add there
// Do any additional setup after loading the view.
}
func configureFacebook()
{
loginBtn.readPermissions = ["public_profile", "email", "user_friends"];
loginBtn.delegate = self
}
option-2
if you add the delegate in directly in your viewcontroller do like for example

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.

Resources