Ich habe eine Startseite, die Benutzer mit Facebook Login einloggen müssen.Aber wenn ich den Facebook-Button antippen - es leitet mich auf Safari-Seite, und es wird automatisch beendet und auf den Startbildschirm zurückzukehren .Nicht einloggen mit Facebook SDK
Ich habe alle Tutorials versucht und den Code geändert. Aber nichts hat für mich funktioniert. Bitte hilf mir - warum passiert das?
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class LoginViewController: UIViewController, UIAlertViewDelegate, GIDSignInDelegate, GIDSignInUIDelegate
{
@IBOutlet weak var UsernameEmailTextField: UITextField? // init username/email text field
@IBOutlet weak var PasswordTextField: UITextField? // init password text field
@IBOutlet var FbLoginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = UIColor.redColor()
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
if (FBSDKAccessToken.currentAccessToken() != nil) {
// User is already logged in, do work such as go to next view controller.
print("User Already Logged In")
} else {
print("User Not Logged In")
}
let dismiss: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.DismissKeyboard))
view.addGestureRecognizer(dismiss)
}
//keyboard dismiss function for input's
func DismissKeyboard() {
view.endEditing(true)
}
//facebook sign in
@IBAction func FbLoginButtonTapped(sender: AnyObject) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logInWithReadPermissions(["email","public_profile","user_location"], fromViewController:self, handler:{(facebookResult, facebookError) -> Void in
if facebookError != nil {
print("Facebook login failed. Error \(facebookError)")
} else if facebookResult.isCancelled {
print("Facebook login was cancelled.")
} else {
if((FBSDKAccessToken.currentAccessToken()) != nil) {
FBSDKGraphRequest(graphPath: "me",
parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email, user_location"]).startWithCompletionHandler({
(connection, result, error) -> Void in
if (error != nil) {
print(error)
} else {
let Email = result.valueForKey("email") as! String
let IdasPassword = result.valueForKey("id") as! String
self.MakeLogin(Email, SocialPassword: IdasPassword)
}
})
}
}
})
}
func MakeLogin(SocialEmail: String, SocialPassword: String) {
//Adding Headers
let headers = ["content-type": "application/x-www-form-urlencoded"]
//Concatenating the email/username field with postdata
let ConcatEmail = "email="+SocialEmail
//Concatenating the password field with postdata
let ConcatPassword = "&password="+SocialPassword
//assigning concatenated values in postData
let postData = NSMutableData(data: ConcatEmail.dataUsingEncoding(NSUTF8StringEncoding)!)
postData.appendData(ConcatPassword.dataUsingEncoding(NSUTF8StringEncoding)!)
//assigning request values
let request = NSMutableURLRequest(URL: NSURL(string: "http login url”)!)
//declaring POST Method
request.HTTPMethod = "POST"
//declaring header fields
request.allHTTPHeaderFields = headers
//Adding postData as HTTPBody
request.HTTPBody = postData
//declaring the session for url
let session = NSURLSession.sharedSession()
//assigning task to get response data
let task = session.dataTaskWithRequest(request, completionHandler: { (ResposeData, response, error) -> Void in
if(ResposeData != nil) {
//declaring completion handler to check whether login.
do {
if let jsonData = try NSJSONSerialization.JSONObjectWithData(ResposeData!, options: []) as? NSDictionary {
//assigning success jsonData
if let success = jsonData["success"] as? Int {
//If login success
if(success == 1) {
//assign access_token value from jsonData
let access_token = jsonData["token"]
// loading menu
dispatch_async(dispatch_get_main_queue()) {
let appdelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
_ = appdelegate.window!.rootViewController
let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController = mainStoryBoard.instantiateViewControllerWithIdentifier("HomeViewController") as! HomeViewController
let leftViewController = mainStoryBoard.instantiateViewControllerWithIdentifier("MenuViewController") as! MenuViewController
let leftSideNav = UINavigationController(rootViewController: leftViewController)
let centerNav = UINavigationController(rootViewController: mainViewController)
let centerContainer:MMDrawerController = MMDrawerController(centerViewController: centerNav, leftDrawerViewController: leftSideNav)
centerContainer.openDrawerGestureModeMask = MMOpenDrawerGestureMode.PanningCenterView;
centerContainer.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.PanningCenterView;
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "ISSOCIALLOGGEDIN")
NSUserDefaults.standardUserDefaults().setValue(access_token, forKey: "access_token")
NSUserDefaults.standardUserDefaults().synchronize()
appdelegate.centerContainer = centerContainer
appdelegate.window!.rootViewController = appdelegate.centerContainer
appdelegate.window!.makeKeyAndVisible()
}
//dismissing the current view
self.dismissViewControllerAnimated(true, completion: nil)
} else {
let ServerMessage = jsonData["message"] as? String
print(ServerMessage)
dispatch_async(dispatch_get_main_queue(), {
let alert = UIAlertController(title: "Error", message: ServerMessage, preferredStyle: UIAlertControllerStyle.Alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
// show the alert
self.presentViewController(alert, animated: true, completion: nil)
})
}
}
} else {
let jsonStr = NSString(data: ResposeData!, encoding: NSUTF8StringEncoding)
// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)
// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: ResposeData!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
dispatch_async(dispatch_get_main_queue(), {
let alert = UIAlertController(title: "Error", message: "No Data Received, Please contact Admin/Dev", preferredStyle: UIAlertControllerStyle.Alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
// show the alert
self.presentViewController(alert, animated: true, completion: nil)
})
}
} else {
print("Error: No Response Data")
dispatch_async(dispatch_get_main_queue(), {
let alert = UIAlertController(title: "Invalid Username or Password", message: "No Response from server, You might be facing internet failure or try with different values", preferredStyle: UIAlertControllerStyle.Alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
// show the alert
self.presentViewController(alert, animated: true, completion: nil)
})
}
})
task.resume()
}
}
irgendein Protokoll ???????? –
Kein Protokoll, kam nur um sich einzuloggen oder Irgendwann ist es nur in Safari Seite – user5513630
bedeutet, dass es abgestürzt ist oder nicht ... –