I have followed the instructions to integrate Facebook login in iOS from here. It worked initially and I was able to login but then it started showing a blank white screen in safari browser(I'm testing it on simulator). I have cleared the cache and and also unblock the cookies.Please help if anyone knows the solution.
Below is the code that I used in loginViewController:
#import "ViewController.h"
#import <FacebookSDK/FacebookSDK.h>
#interface ViewController ()
#property (strong, nonatomic) IBOutlet FBProfilePictureView *profilePictureView;
#property (strong, nonatomic) IBOutlet UILabel *nameLabel;
#property (strong, nonatomic) IBOutlet UILabel *statusLabel;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
FBLoginView *loginView = [[FBLoginView alloc] initWithReadPermissions:#[#"basic_info", #"email", #"user_likes"]];
loginView.frame = CGRectOffset(loginView.frame, (self.view.center.x - (loginView.frame.size.width / 2)), 5);
loginView.delegate = self;
[self.view addSubview:loginView];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// This method will be called when the user information has been fetched
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
self.profilePictureView.profileID = user.id;
self.nameLabel.text = user.name;
}
// Logged-in user experience
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView {
self.statusLabel.text = #"You're logged in as";
}
// Logged-out user experience
- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView {
self.profilePictureView.profileID = nil;
self.nameLabel.text = #"";
self.statusLabel.text= #"You're not logged in!";
}
// Handle possible errors that can occur during login
- (void)loginView:(FBLoginView *)loginView handleError:(NSError *)error {
NSString *alertMessage, *alertTitle;
// If the user should perform an action outside of you app to recover,
// the SDK will provide a message for the user, you just need to surface it.
// This conveniently handles cases like Facebook password change or unverified Facebook accounts.
if ([FBErrorUtility shouldNotifyUserForError:error]) {
alertTitle = #"Facebook error";
alertMessage = [FBErrorUtility userMessageForError:error];
// This code will handle session closures that happen outside of the app
// You can take a look at our error handling guide to know more about it
// https://developers.facebook.com/docs/ios/errors
} else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession) {
alertTitle = #"Session Error";
alertMessage = #"Your current session is no longer valid. Please log in again.";
// If the user has cancelled a login, we will do nothing.
// You can also choose to show the user a message if cancelling login will result in
// the user not being able to complete a task they had initiated in your app
// (like accessing FB-stored information or posting to Facebook)
} else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
NSLog(#"user cancelled login");
// For simplicity, this sample handles other errors with a generic message
// You can checkout our error handling guide for more detailed information
// https://developers.facebook.com/docs/ios/errors
} else {
alertTitle = #"Something went wrong";
alertMessage = #"Please try again later.";
NSLog(#"Unexpected error:%#", error);
}
if (alertMessage) {
[[[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
}
#end
Related
I need to integrate GMail inbox in my application after authentication.So how can I query the inbox content of GMail by using the API. And also I have to access the other features too.So Please help me to find the exact swift code to access the GMail.
Using Google Docs iOS Quickstart:
Step 1: Turn on the Gmail API
Step 2: Prepare the workspace
Step 3: Set up the sample
Here is a sample code, replace the contents of the ViewController.h file with the following code:
#import <UIKit/UIKit.h>
#import "GTMOAuth2ViewControllerTouch.h"
#import "GTLGmail.h"
#interface ViewController : UIViewController
#property (nonatomic, strong) GTLServiceGmail *service;
#property (nonatomic, strong) UITextView *output;
#end
Replace the contents of ViewController.m with the following code:
#import "ViewController.h"
static NSString *const kKeychainItemName = #"Gmail API";
static NSString *const kClientID = #"YOUR_CLIENT_ID_HERE";
#implementation ViewController
#synthesize service = _service;
#synthesize output = _output;
// When the view loads, create necessary subviews, and initialize the Gmail API service.
- (void)viewDidLoad {
[super viewDidLoad];
// Create a UITextView to display output.
self.output = [[UITextView alloc] initWithFrame:self.view.bounds];
self.output.editable = false;
self.output.contentInset = UIEdgeInsetsMake(20.0, 0.0, 20.0, 0.0);
self.output.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[self.view addSubview:self.output];
// Initialize the Gmail API service & load existing credentials from the keychain if available.
self.service = [[GTLServiceGmail alloc] init];
self.service.authorizer =
[GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
clientID:kClientID
clientSecret:nil];
}
// When the view appears, ensure that the Gmail API service is authorized, and perform API calls.
- (void)viewDidAppear:(BOOL)animated {
if (!self.service.authorizer.canAuthorize) {
// Not yet authorized, request authorization by pushing the login UI onto the UI stack.
[self presentViewController:[self createAuthController] animated:YES completion:nil];
} else {
[self fetchLabels];
}
}
// Construct a query and get a list of labels from the user's gmail. Display the
// label name in the UITextView
- (void)fetchLabels {
self.output.text = #"Getting labels...";
GTLQueryGmail *query = [GTLQueryGmail queryForUsersLabelsList];
[self.service executeQuery:query
delegate:self
didFinishSelector:#selector(displayResultWithTicket:finishedWithObject:error:)];
}
- (void)displayResultWithTicket:(GTLServiceTicket *)ticket
finishedWithObject:(GTLGmailListLabelsResponse *)labelsResponse
error:(NSError *)error {
if (error == nil) {
NSMutableString *labelString = [[NSMutableString alloc] init];
if (labelsResponse.labels.count > 0) {
[labelString appendString:#"Labels:\n"];
for (GTLGmailLabel *label in labelsResponse.labels) {
[labelString appendFormat:#"%#\n", label.name];
}
} else {
[labelString appendString:#"No labels found."];
}
self.output.text = labelString;
} else {
[self showAlert:#"Error" message:error.localizedDescription];
}
}
// Creates the auth controller for authorizing access to Gmail API.
- (GTMOAuth2ViewControllerTouch *)createAuthController {
GTMOAuth2ViewControllerTouch *authController;
// If modifying these scopes, delete your previously saved credentials by
// resetting the iOS simulator or uninstall the app.
NSArray *scopes = [NSArray arrayWithObjects:kGTLAuthScopeGmailReadonly, nil];
authController = [[GTMOAuth2ViewControllerTouch alloc]
initWithScope:[scopes componentsJoinedByString:#" "]
clientID:kClientID
clientSecret:nil
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
return authController;
}
// Handle completion of the authorization process, and update the Gmail API
// with the new credentials.
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)authResult
error:(NSError *)error {
if (error != nil) {
[self showAlert:#"Authentication Error" message:error.localizedDescription];
self.service.authorizer = nil;
}
else {
self.service.authorizer = authResult;
[self dismissViewControllerAnimated:YES completion:nil];
}
}
// Helper for showing an alert
- (void)showAlert:(NSString *)title message:(NSString *)message {
UIAlertView *alert;
alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
#end
Step 4: Run the sample
Notes: Authorization information is stored in your Keychain, so subsequent executions will not prompt for authorization.
You can review and learn more about iOS and Google API(GMAIL API) in https://developers.google.com/gmail/api/v1/reference/ to apply other feature you want to add.
I hope this helps :)
FBSDKGameRequestContent *content = [[FBSDKGameRequestContent alloc]init];
content.message = #"Great FB";
content.title = #"Invite Friends";
FBSDKGameRequestDialog *gameDialog = [[FBSDKGameRequestDialog alloc]init];
gameDialog.content = content;
gameDialog.frictionlessRequestsEnabled = YES;
gameDialog.delegate = self;
if ([gameDialog canShow]) {
[gameDialog show];
}
I am using the above code for showing FBFriends. The dialog is opened, but I want to perform some of my custom functionality after user hits send/cancel.
How should I do it?
You're doing:
gameDialog.delegate = self;
So, why don't you use the delegate methods (FBSDKGameRequestDialogDelegate): gameRequestDialogDidCancel: and
gameRequestDialog:didCompleteWithResults: to know if user has cancelled of sent its invitation?
Source
In your YourCurrentClass.h:
#interface YourCurrentClass : NSObject < FBSDKGameRequestDialogDelegate >
In your YourCurrentClass.m:
- (void)gameRequestDialog:(FBSDKGameRequestDialog *)gameRequestDialog
didCompleteWithResults:(NSDictionary *)results
{
//User has done something.
//Check "results" and do something.
}
- (void)gameRequestDialogDidCancel:(FBSDKGameRequestDialog *)gameRequestDialog
{
//User has cancelled
//Do somathing
}
- (void)gameRequestDialog:(FBSDKGameRequestDialog *)gameRequestDialog
didFailWithError:(NSError *)error
{
//An error happened
NSLog(#"Error: %#", error);
//Do something
}
I want to retrieve basic information like name, email from Google account. Here Get User information after successful authentication with Oauth2 I've found tip to change the property "shouldFetchGoogleUserProfile" to YES, but it's not accessible for me.
GTMOAuth2ViewControllerTouch *viewController;
viewController = [[GTMOAuth2ViewControllerTouch alloc] initWithScope:scope
clientID:kMyClientID
clientSecret:kMyClientSecret
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
// error - can't access property "shouldFetchGoogleUserProfile"
viewController.signIn.shouldFetchGoogleUserProfile = YES;
[[self navigationController] pushViewController: viewController
animated:YES];
I cannot also get the result after sign-in
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if (!error) {
// userProfile - not accessible
// NSDictionary *profile = viewController.signIn.userProfile;
} else {
NSLog(#"Failure %#", error);
}
}
I had this same issue. Add
#import "GTL/GTMOAuth2SignIn.h"
to the bridging header which is the class for signIn.
The header:
#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>
#interface ViewController : UIViewController<UITextFieldDelegate>
{
IBOutlet UITextField *update;
NSString *status;
}
#property (nonatomic, copy) IBOutlet NSString *status;
#end
.m File:
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UIButton *buttonPostStatus;
#property (strong, nonatomic) id<FBGraphUser> loggedInUser;
#property (strong, nonatomic) IBOutlet UILabel *labelFirstName;
#property (strong,nonatomic) IBOutlet UITextField *update;
#property (strong,nonatomic) IBOutlet UILabel *dob;
#property (strong,nonatomic) IBOutlet UILabel *profilename;
- (IBAction)postStatusUpdateClick:(UIButton *)sender;
#end
#implementation ViewController
#synthesize buttonPostStatus = _buttonPostStatus;
#synthesize loggedInUser = _loggedInUser;
#synthesize labelFirstName = _labelFirstName;
#synthesize update;
#synthesize dob;
#synthesize profilename;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
FBLoginView *loginview = [[FBLoginView alloc] init];
loginview.frame = CGRectOffset(loginview.frame, 5, 5);
if ([self respondsToSelector:#selector(setEdgesForExtendedLayout:)]) {
loginview.frame = CGRectOffset(loginview.frame, 5, 25);
}
loginview.delegate = self;
self.labelFirstName = nil;
self.loggedInUser = nil;
[self.view addSubview:loginview];
[loginview sizeToFit];
NSString *status = update.text;
}
- (void)viewDidUnload {
self.buttonPostStatus = nil;
[super viewDidUnload];
}
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
self.labelFirstName.text = [NSString stringWithFormat:#"Hello %# %#", user.first_name, user.last_name ];
self.loggedInUser = user;
self.dob.text= [NSString stringWithFormat:#"Birthday- %#", user.birthday];
NSLog(user.birthday);
NSLog(self.labelFirstName.text);
//NSLog(user.dob);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)loginView:(FBLoginView *)loginView handleError:(NSError *)error {
NSLog(#"FBLoginView encountered an error=%#", error);
}
- (void) performPublishAction:(void (^)(void)) action {
// we defer request for permission to post to the moment of post, then we check for the permission
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
// if we don't already have the permission, then we request it now
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
} else if (error.fberrorCategory != FBErrorCategoryUserCancelled){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Permission denied"
message:#"Unable to get permission to post"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
} else {
action();
}
}
- (IBAction)postStatusUpdateClick:(UIButton *)sender {
NSURL *urlToShare = [NSURL URLWithString:#"htts.facebook.com/ios"];
FBAppCall *appCall = [FBDialogs presentShareDialogWithLink:urlToShare
name:#"Hello Facebook"
caption:nil
description:#"The 'Hello Facebook' sample application showcases simple Facebook integration."
picture:nil
clientState:nil
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if (error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success!");
}
}];
[self performPublishAction:^{
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
connection.errorBehavior = FBRequestConnectionErrorBehaviorReconnectSession
| FBRequestConnectionErrorBehaviorAlertUser
| FBRequestConnectionErrorBehaviorRetry;
[connection addRequest:[FBRequest requestForPostStatusUpdate:update.text]
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:update.text result:result error:error];
self.buttonPostStatus.enabled = YES;
}];
[connection start];
self.buttonPostStatus.enabled = NO;
}];
}
- (void)showAlert:(NSString *)message
result:(id)result
error:(NSError *)error {
NSString *alertMsg;
NSString *alertTitle;
if (error) {
alertTitle = #"Error";
if (error.fberrorUserMessage && FBSession.activeSession.isOpen) {
alertTitle = nil;
} else {
// Otherwise, use a general "connection problem" message.
alertMsg = #"Operation failed due to a connection problem, retry later.";
}
} else {
NSDictionary *resultDict = (NSDictionary *)result;
alertMsg = [NSString stringWithFormat:#"Successfully posted '%#'.", update.text];
NSString *postId = [resultDict valueForKey:#"id"];
if (!postId) {
postId = [resultDict valueForKey:#"postId"];
}
if (postId) {
alertMsg = [NSString stringWithFormat:#"%#\nPost ID: %#", alertMsg, postId];
}
alertTitle = #"Ho Gya!!";
}
if (alertTitle) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMsg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
#end
I want to get the user information like username, email id, birthday etc.. whenever the user logs in.
I am trying to get the info of user by this code. Am I correct or not? If something is missing in this code, please provide some coding solution.
You have to set Permission for that
loginview.readPermissions=#[#"email"];
All I want to do in my code is move from one view to another. No matter how many different ways I try to go around it, any segue or any change from the current view causes this error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
There's no indication of what object it's talking about at all, and the app is crashing on my segue line. Oh and I'm using Xcode 5-DP and iOS 7. Here's my source:
LoginViewController.h
#import <UIKit/UIKit.h>
#import "ECSlidingViewController.h"
#import "MenuViewController.h"
#import <MessageUI/MessageUI.h>
#import <CoreData/CoreData.h>
#interface LoginViewController : UIViewController <UITextFieldDelegate>
#property (weak, nonatomic) IBOutlet UITextField *userTextField;
#property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
- (IBAction)signupTouched:(UIButton *)sender;
- (IBAction)logInPressed:(id)sender;
- (IBAction)backgroundTouched:(id)sender;
- (IBAction)revealMenu:(id)sender;
#end
LoginViewController.m (Exception on line 8)
#import "LoginViewController.h"
#import "RegisterView.h"
#import <Parse/Parse.h>
#implementation LoginViewController
- (IBAction)signupTouched:(UIButton *)sender {
[self performSegueWithIdentifier:#"signup" sender:self];
// THE APPLICATION CRASHES ON THIS LINE ABOVE
}
//Login button pressed
-(IBAction)logInPressed:(id)sender
{
//If user logged succesful:
//[self performSegueWithIdentifier:#"LoginSuccesful" sender:self];
if (![self.userTextField.text isEqual:#""]) {
[PFUser logInWithUsernameInBackground:self.userTextField.text password:self.passwordTextField.text block:^(PFUser *user, NSError *error) {
if (user) {
//Open the wall
//[self performSegueWithIdentifier:#"LoginSuccesful" sender:self];
UIAlertView *loginAlertView = [[UIAlertView alloc] initWithTitle:#"Great!" message:#"You have logged in" delegate:nil cancelButtonTitle:#"Get roaming" otherButtonTitles:nil, nil];
[loginAlertView show];
} else {
//Something bad has ocurred
NSString *errorString = [[error userInfo] objectForKey:#"error"];
UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[errorAlertView show];
}
}];
} else {
//Something bad has ocurred
NSString *errorString = #"You did not type any credentials!";
UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil, nil];
[errorAlertView show];
}
}
- (IBAction)backgroundTouched:(id)sender {
[self.userTextField resignFirstResponder];
[self.passwordTextField resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (![self.slidingViewController.underLeftViewController isKindOfClass:[MenuViewController class]]) {
self.slidingViewController.underLeftViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"Menu"];
}
self.slidingViewController.underRightViewController = nil;
[self.view addGestureRecognizer:self.slidingViewController.panGesture];
}
- (IBAction)revealMenu:(id)sender
{
[self.slidingViewController anchorTopViewTo:ECRight];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.userTextField.delegate = self;
self.passwordTextField.delegate = self;
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidUnload {
[self setUserTextField:nil];
[self setPasswordTextField:nil];
[super viewDidUnload];
}
#end
I've googled, and I've googled. No-one else seems to be having an issue like this. I tried cleaning out my entire iOS Simulator and everything to no avail, following a solution that appeared to work for others. I've tried every type of segue possible and none are working.
Thanks in advance!
Recheck your configuration and use of the ECSlidingViewController, and it's topViewController.
Check in signup.xib if the UIView is connected to an outlet.