Not able to Login in Facebook using Parse Objective C - ios

I am using Parse in my application. I am try to login with Facebook. But I have faced one strange issue. If I am login in Facebook account from my iPhone's settings, then I am getting following error.
Error Domain=com.facebook.sdk Code=2 "The operation couldn’t be completed. (com.facebook.sdk error 2.)" UserInfo=0x17560700 {com.facebook.sdk:ErrorLoginFailedReason=com.facebook.sdk:SystemLoginCancelled, com.facebook.sdk:ErrorInnerErrorKey=Error Domain=com.apple.accounts Code=7 "The operation couldn’t be completed. (com.apple.accounts error 7.)", com.facebook.sdk:ErrorSessionKey=<FBSession: 0x175227e0, state: FBSessionStateClosedLoginFailed, loginHandler: 0x0, appID: 638916992864352, urlSchemeSuffix: , tokenCachingStrategy:<PFFacebookTokenCachingStrategy: 0x175a9900>, expirationDate: (null), refreshDate: (null), attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(null)>}
I am logout from iPhone's Settings->Facebook then its working fine.
I have done research on it, but not getting solutions.
Can anyone help to solve my issue ?
Thanks,

Try with below code..You need to give permissions in the code as in below code..
-(IBAction)facebookButtonAction:(id)sender
{
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
self.accountStore = [[ACAccountStore alloc] init];
// Create an account type that ensures Twitter accounts are retrieved.
ACAccountType *accountType = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSArray * permissions = [NSArray arrayWithObjects:#"email",#"user_location",#"user_birthday", nil];
NSDictionary * dict=[NSDictionary dictionaryWithObjectsAndKeys:#“xxxxxxxxxxxxxxx,ACFacebookAppIdKey,permissions,ACFacebookPermissionsKey,ACFacebookAudienceEveryone,ACFacebookAudienceKey, nil];
[self.accountStore requestAccessToAccountsWithType:accountType options:dict completion:^(BOOL granted, NSError *error) {
NSLog(#"-------------error =%#--------- check grant bol %d",error,granted);
if(granted ) {
NSArray *accountsArray = [self.accountStore accountsWithAccountType:accountType];
if ([accountsArray count] > 0)
{
ACAccount *fbAccount = [accountsArray objectAtIndex:0];
NSDictionary *tempDict = [[NSMutableDictionary alloc] initWithDictionary:[fbAccount dictionaryWithValuesForKeys:[NSArray arrayWithObject:#"properties"]]];
NSString *facebookname;
facebookname=#"Name not found";
facebookname = [[tempDict objectForKey:#"properties"] objectForKey:#"ACPropertyFullName"];
if ([facebookname isKindOfClass:[NSNull class]] || facebookname==NULL || [facebookname isEqualToString:#""] || [facebookname isEqualToString:#"(null)"])
{
facebookname = [[tempDict objectForKey:#"properties"] objectForKey:#"fullname"];
}
//if (SYSTEM_VERSION_LESS_THAN(#"7.0"))
{
}
NSString *facebookID = [NSString stringWithFormat:#"%#", [[fbAccount valueForKey:#"properties"] valueForKey:#"uid"]] ;
NSString *pictureURL=[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1",facebookID];
NSLog(#" check the properties %#",tempDict);
NSLog(#" name nemae %#",facebookname);
NSLog(#" facebookID %#",facebookID);
NSLog(#" image https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1",facebookID);
if ([facebookname isKindOfClass:[NSNull class]] || facebookname==NULL || [facebookname isEqualToString:#""] || [facebookname isEqualToString:#"(null)"])
{
UIAlertView *somethingerr=[[UIAlertView alloc]initWithTitle:#“App Name” message:#"Something went wrong with facebook login. Please send your console report to the developers." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[somethingerr show
];
[self hidespinner];
return;
}
}
else{
UIAlertView *alerts=[[UIAlertView alloc]initWithTitle:#"No facebok account" message:#"Please add or create an account in \"settings \" " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alerts show];
[self performSelector:#selector(hidespinner) withObject:nil afterDelay:0.1] ;
}
}
else{
switch ([error code])
{
case 0:
[self showErrorAlertWithMessage:#"Unknown error occured, try again later!"];
break;
case 1:
[self showErrorAlertWithMessage:#"Unknown error occured, try again later!"];
break;
case 3:
[self showErrorAlertWithMessage:#"Authentication failed, try again later!"];
break;
case 6:
[self showErrorAlertWithMessage:#"Facebook account does not exists. Please create it in Settings and come back!"];
break;
case 7:
[self showErrorAlertWithMessage:#"Permission request failed. You won't be able to share information to Facebook"];
break;
default:
[self performSelector:#selector(hidespinner) withObject:Nil afterDelay:0.1];
break;
}
}
}];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Facebook Accounts" message:#"There are no Facebook accounts configured. You can add or create a Facebook account in Settings." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[self performSelector:#selector(hidespinner) withObject:nil afterDelay:0.1] ;
}
}
Hope it helps you....!

Related

xmpp stream did disconnect Calling after connect in ios?

Hi I am working with the xmpp framework working fine till yesterday But I don't know what happen suddenly xmpp didDisConnect method calling
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
where I am missing.I know if username password wrong then it will be disconnected.But I checked my username it is fine and it is showing below error
Error Domain=GCDAsyncSocketErrorDomain Code=4 "Read operation timed out" UserInfo={NSLocalizedDescription=Read operation timed out
below is the connect method
- (BOOL)connect
{
if (![xmppStream isDisconnected]) {
return YES;
}
myJID =[NSString stringWithFormat:#"%##servername",[[NSUserDefaults standardUserDefaults] stringForKey:#"FinalUserNameJID"]];
NSString *password1=[[NSUserDefaults standardUserDefaults] stringForKey:#"smsVerificationNumber"];
// If you don't want to use the Settings view to set the JID,
// uncomment the section below to hard code a JID and password.
//
// myJID = #"user#gmail.com/xmppframework";
// myPassword = #"";
if (myJID == nil || password1 == nil) {
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
password = password1;
NSError *error = nil;
if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error connecting"
message:#"See console for error details."
delegate:nil
cancelButtonTitle:NSLocalizedString( #"O_K", #"OK")
otherButtonTitles:nil];
[alertView show];
DDLogError(#"Error connecting: %#", error);
return NO;
}
return YES;
}
Please help me if any body face this issue.Thankyou

iOS login segue fix

This is the success parameter to my login which is under the closing bracket in viewDidload
//check whether it's a login or register
NSString* command = (sender.tag==1)?#"register":#"login";
NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:command, #"command", fldUsername.text, #"username", hashedPassword, #"password", nil];
//make the call to the web API
[[API sharedInstance] commandWithParams:params onCompletion:^(NSDictionary *json) {
//result returned
NSDictionary* res = [[json objectForKey:#"result"] objectAtIndex:0];
if ([json objectForKey:#"error"]==nil && [[res objectForKey:#"IdUser"] intValue]>0) {
[[API sharedInstance] setUser: res];
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
//show message to the user
[[[UIAlertView alloc] initWithTitle:#"Logged in" message:[NSString stringWithFormat:#"Welcome %#",[res objectForKey:#"username"]] delegate:nil cancelButtonTitle:#"Close" otherButtonTitles: nil] show];
} else {
//error
[UIAlertView error:[json objectForKey:#"error"]];
}
}];
}
And this is the programatic connection in the view that I want to show when the user is authorized
-(void)viewDidload
[super viewDidLoad];
{
if (![[API sharedInstance] isAuthorized]) {
[self performSegueWithIdentifier:#"ShowLogin" sender:nil];
}
The problem is when I enter saved logged in credentials in my database (i.e. username: user1 password: password) I get the correct UIAlert I'm supposed to receive (Logged in - Welcome user1). But when i enter (username:user1 password: fake password) I still get the logged in UIAlert. Also if i try to register a new user from the app i.e. (username:user2 password: password 2) I get an authentication failed UIAlert. Also my segue doesn't actually happen when I enter valid credentials. Any tips?
Updated: logout delegate
-(void)logout {
//logout the user from the server, and also upon success destroy the local authorization
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:#"logout", #"command", nil] onCompletion:^(NSDictionary *json) {
//logged out from server
[API sharedInstance].user = nil;
[self performSegueWithIdentifier:#"ShowLogin" sender:nil];
}];
}
[[API sharedInstance] commandWithParams:params onCompletion:^(NSDictionary *json) {
//result returned
NSDictionary* res = [[json objectForKey:#"result"] objectAtIndex:0];
if ([json objectForKey:#"error"]==nil && [[res objectForKey:#"IdUser"] intValue]>0) {
[[API sharedInstance] setUser: res];
[API sharedInstance].isAuthorized = YES; //Added
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
//show message to the user
[[[UIAlertView alloc] initWithTitle:#"Logged in" message:[NSString stringWithFormat:#"Welcome %#",[res objectForKey:#"username"]] delegate:nil cancelButtonTitle:#"Close" otherButtonTitles: nil] show];
} else {
[[API sharedInstance] setUser: nil]; //Added
[API sharedInstance].isAuthorized = NO; //Added
//error
[UIAlertView error:[json objectForKey:#"error"]];
}
}];
Find the lines with inline comments //Added and try those in your code. Also as mentioned update login view -> viewWillAppear and logout method.
Hope this helps.

iOS 8 adding contact to address book

I'm trying to add a contact to the address book in iOS8. Unable to do so anymore. Here's my code below:
-(void)addPersonToAddressBook {
NSString * fullName = integrationDictionary[#"fullName"];
ABPeoplePickerNavigationController *pp =[ABPeoplePickerNavigationController new];
ABAddressBookRef addressBook = [pp addressBook];
ABRecordRef entry = ABPersonCreate();
CFErrorRef cfError=nil;
ABRecordSetValue(entry, kABPersonFirstNameProperty, (__bridge CFTypeRef)(fullName) , nil);
ABAddressBookAddRecord(addressBook, entry, &cfError);
if (ABAddressBookSave(addressBook, &cfError)) {
NSString *saveMessage = [NSString stringWithFormat:#"%# has been added to your address book.", fullName];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Contact Added" message:saveMessage delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
} else {
NSString *saveMessage = [NSString stringWithFormat:#"There was an error adding %# to your address book.", fullName];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Uh Oh" message:saveMessage delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
NSLog(#"error is %#", cfError);
The error is showing up as null. Has anyone seen this before? Any workarounds?
The error is returning NULL because there's no error registered.
The problem is that [pp addressBook] is returning nil. So your ABAddressBookRef addressBook reference is nil.
The workaround is to use ABAddressBookCreateWithOptions instead of [pp addressBook] method of ABPeoplePickerNavigationController.
Here's a sample which works just fine on both iOS 7.1 & iOS 8.1:
-(void)requestAuthorizationAndAddPersonToAddressBook
{
// Request authorization to Address Book
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
// First time access has been granted, add the contact
[self addPersonToAddressBook];
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, add the contact
[self addPersonToAddressBook];
}
else {
// The user has previously denied access
// Send an alert telling user to change privacy setting in settings app
}
}
-(void)addPersonToAddressBook {
NSString * fullName = #"James Bond";
CFErrorRef abCreateError = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &abCreateError);
if (abCreateError) {
NSLog(#"Error occurred: %#", abCreateError);
}
ABRecordRef entry = ABPersonCreate();
CFErrorRef cfError=nil;
ABRecordSetValue(entry, kABPersonFirstNameProperty, (__bridge CFTypeRef)(fullName) , nil);
ABAddressBookAddRecord(addressBook, entry, &cfError);
if (ABAddressBookSave(addressBook, &cfError)) {
NSString *saveMessage = [NSString stringWithFormat:#"%# has been added to your address book.", fullName];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Contact Added" message:saveMessage delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
} else {
NSString *saveMessage = [NSString stringWithFormat:#"There was an error adding %# to your address book.", fullName];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Uh Oh" message:saveMessage delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
if (cfError) {
NSLog(#"error is %#", cfError);
}
}

how to use Gmail smtp in iOS app

I am new to Xcode I need an app to send a email. Background: the destination email Id is typed in a text and by clicking the send button the message body Sample should go to the destination Email ID I tried this code in the function button clicked but it is not working when ever i try this code I get error in function can any one guide me with a step by step tutorial
mailTransfer[673:207] delegate - error(-5): timeout sending message
2014-07-05 10:54:05.393 mailTransfer[673:207] * stopping watchdog * I had added the SMTP files from google documents ... any other way to correct this code
- (IBAction)sendMessageInBack:(id)anObject
{
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail = #"Yours mail ids";
testMsg.toEmail = emailField.text;
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = #"Your mail ids";
testMsg.pass = #"id password";
testMsg.subject = #"Test application ";
testMsg.wantsSecure = YES;
testMsg.delegate = self;
NSDictionary *plainPart = [NSDictionarydictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,#"Sample",kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
[testMsg send];
}
-(void)messageSent:(SKPSMTPMessage *)message{
[message release];
NSLog(#"delegate - message sent");
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
[message release];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Unable to send email" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
in SKPSMTPMessage.m
update the following line
CFDictionarySetValue(sslOptions,kCFStreamSSLLevel,kCFStreamSocketSecurityLevelTLSv1);
with
CFDictionarySetValue(sslOptions, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv3);
Download SMTP framework and import SKPSMTPMessage class..
#import "SKPSMTPMessage.h"
-(void)sendEmailVideo:(NSString*)_toEmailAddress andCC:(NSString*)ccEmail
{
#try
{
// Message =[data getContentOfPanic];
NSData *webData = [NSData dataWithContentsOfURL:videoURL];
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail=#"nikki.varsha#gmail.com";//sender email address
emailMessage.toEmail=_toEmailAddress;
//receiver email address
emailMessage.relayHost=#"smtp.gmail.com";
//emailMessage.ccEmail =ccEmail;
emailMessage.requiresAuth = YES;
emailMessage.login = #"nikki.varsha#gmail.com"; //sender email address
emailMessage.pass = #"123";
//sender email password
emailMessage.subject =#"Panic Video Message";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self;
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
Message,kSKPSMTPPartMessageKey,#"8bit", kSKPSMTPPartContentTransferEncodingKey,nil];
NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"Video.mov\"",kSKPSMTPPartContentTypeKey,
#"attachment;\r\n\tfilename=\"Video.mov\"",kSKPSMTPPartContentDispositionKey,[webData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts=[NSArray arrayWithObjects:plainPart,vcfPart,nil];
dispatch_queue_t backgroundVideoQueue = dispatch_queue_create("com.VideoQue", 0);
dispatch_sync(backgroundVideoQueue, ^{
[emailMessage send];
});
}
#catch (NSException *exception)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Host" message:#"No Reciever Email Ids Available! " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
pragma mark - sendEmail delegate (SKPSMTPMessage)
-(void)messageSent:(SKPSMTPMessage *)message
{
NSLog(#"delegate - Email sent");
NSLog(#"Mesg %#",message);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Email sent." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"err=%#" ,message);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Unable to send email Please Check EmailId & Password"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
});
}
in SKPSMTPMessage.m file do change the following line
Remove this line
//CFDictionarySetValue(sslOptions,kCFStreamSSLLevel,kCFStreamSocketSecurityLevelTLSv1);
Add this line
CFDictionarySetValue(sslOptions, kCFStreamSSLLevel, kCFStreamSocketSecurityLevelSSLv3);
Thanks

Need suggestion to integrate gmail account in iOS developlment

I am new to iOS programming, and just want to do something fun.
I want to develop a mail client app for iPhone, it can add email accounts such as gmail and Yahoo and so on. I searched online for a while and also find some answers, before I dive into the details I just want someone who has similar experience give me some suggestions about which method is the best.
thanks
I have recently implemented gmail api to fetch gmail contacts and their email in my tableview. Gmail api is depricated, thats why you might have not got any proper documentation for that.
To implement gmail use libGDataTouchStaticLib.a library, with Gdata headers (search on google for that otherwise send me your email i will send you its zip).
The code to get gmail details are as follows
- (void)getGoogleContacts {
GDataServiceGoogleContact *service = [self contactService];
GDataServiceTicket *ticket;
BOOL shouldShowDeleted = TRUE;
// request a whole buncha contacts; our service object is set to
// follow next links as well in case there are more than 2000
const int kBuncha = 2000;
NSURL *feedURL = [GDataServiceGoogleContact contactFeedURLForUserID:kGDataServiceDefaultUser];
GDataQueryContact *query = [GDataQueryContact contactQueryWithFeedURL:feedURL];
[query setShouldShowDeleted:shouldShowDeleted];
[query setMaxResults:kBuncha];
ticket = [service fetchFeedWithQuery:query
delegate:self
didFinishSelector:#selector(contactsFetchTicket:finishedWithFeed:error:)];
[self setContactFetchTicket:ticket];
}
- (void)setContactFetchTicket:(GDataServiceTicket *)ticket {
mContactFetchTicket = ticket;
}
- (GDataServiceGoogleContact *)contactService {
static GDataServiceGoogleContact* service = nil;
if (!service) {
service = [[GDataServiceGoogleContact alloc] init];
[service setShouldCacheResponseData:YES];
[service setServiceShouldFollowNextLinks:YES];
}
// update the username/password each time the service is requested
NSString *username = [txtUserName text];
NSString *password = [txtPasswrod text];
[service setUserCredentialsWithUsername:username
password:password];
return service;
}
// contacts fetched callback
- (void)contactsFetchTicket:(GDataServiceTicket *)ticket
finishedWithFeed:(GDataFeedContact *)feed
error:(NSError *)error {
if (error) {
NSDictionary *userInfo = [error userInfo];
NSLog(#"Contacts Fetch error :%#", [userInfo objectForKey:#"Error"]);
if ([[userInfo objectForKey:#"Error"] isEqual:#"BadAuthentication"]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Authentication Failed"
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Failed to get Contacts."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
}
} else {
NSArray *contacts = [feed entries];
NSLog(#"Contacts Count: %d ", [contacts count]);
[mutAryGoogleContacts removeAllObjects];
for (int i = 0; i < [contacts count]; i++) {
NSMutableDictionary *aDictContactDetails=[NSMutableDictionary dictionary];
GDataEntryContact *contact = [contacts objectAtIndex:i];
// Email
GDataEmail *email = [[contact emailAddresses] objectAtIndex:0];
NSString* ContactEmail = [email address];
if (ContactEmail) {
[aDictContactDetails setObject:ContactEmail forKey:#"email"];
// Name
NSString *ContactName = [[[contact name] fullName] contentStringValue];
if (ContactName) {
[aDictContactDetails setObject:ContactName forKey:#"friendName"];
}
[mutAryGoogleContacts addObject:aDictContactDetails];
}
}
//Push to next vc or do whatever you want
}
}

Resources