My application used notify of APNS. When server send a notify to client with a link. I click to notify on notification bar, application will open link in notify on webview. My problem is, when application run active or Background, it run normal and load link OK. But when application don't active, i click to notify, it will don't load link in notify, it only load old link in NSUserDefaults or link "http://staging.nhomxe.vn". This is my code:
APPDELEGATE.m
- (void)application:(UIApplication*)application
didReceiveRemoteNotification:
(NSDictionary*)userInfo
{
NSLog(#"Received notification: %#", userInfo);
NSDictionary *data = [ userInfo objectForKey:#"aps"];
for(NSString *key in data) {
NSString *info = [data objectForKey:key];
NSLog(#"thong tin nhan dc: %# : %#", key, info);
}
NSString *message = [userInfo valueForKey:#"link"] ;
//NSArray *info = [message componentsSeparatedByString:#"&#"];
//NSString *body = [info objectAtIndex:0];
//NSString *link = [info objectAtIndex:1];
NSLog(#"Thong tin Link: %#",message);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:message forKey:#"LINK"];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Warning"
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alertView show];
ViewController *vc = (ViewController *)self.window.rootViewController;
NSURL *url = [NSURL URLWithString:message];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[vc.webView loadRequest:urlRequest];
[vc.webView3 loadRequest:urlRequest];
}
MYVIEWCONTROLLER.m
- (void)viewDidLoad
{ NSString *link = NULL;
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
link = [data objectForKey:#"LINK"];
NSString *connect = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://staging.nhomxe.vn"] encoding:NSUTF8StringEncoding error:nil];
if(connect == NULL)
{
NSLog(#"Server hiện tại đang bảo trì. Ứng dụng sẽ đóng ngay bây giờ.!");
UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:#"Warning"
message:#"Server hiện tại đang bảo trì. Ứng dụng sẽ đóng ngay bây giờ."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
alert.tag = 1;
[alert show];
}else
{ if(link == NULL)
{
NSString *linkWeb = #"http://staging.nhomxe.vn";
NSURL *url = [NSURL URLWithString:linkWeb];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:urlRequest];
[self.webView3 loadRequest:urlRequest];
}else{
NSURL *url = [NSURL URLWithString:link];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:urlRequest];
[self.webView3 loadRequest:urlRequest];
//[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"LINK"];
//[[NSUserDefaults standardUserDefaults] synchronize];
//NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//[defaults setValue:NULL forKey:#"LINK"];
}
}
// Schedule the runScheduledTask in 5 seconds
aTimer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:#selector(runScheduledTask) userInfo:nil repeats:YES];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
When App is not running in Background
- (void)application:(UIApplication*)application
didReceiveRemoteNotification:
(NSDictionary*)userInfo
Would not be called you Should handle your data something like this..
In your AppDelegate.m within didFinishLaunchingWithOptions method do something like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSDictionary* userInfo = [launchOptions valueForKey:#"UIApplicationLaunchOptionsRemoteNotificationKey"];
NSDictionary * data = [userInfo objectForKey:#"aps"];
for(NSString *key in data) {
NSString *info = [data objectForKey:key];
NSLog(#"thong tin nhan dc: %# : %#", key, info);
}
//.…COntinue with your Execution So on…. You will get the data in the Data Dictionary which you are looking for
}
I suspect you don't have code to start app from notification.
Take a look at - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions. If app starts from notification, you'll have launchOptions.
If you have remote notification, you'll have UIApplicationLaunchOptionsRemoteNotificationKey key in launchOptions.
UIApplicationLaunchOptionsRemoteNotificationKey
The presence of this key indicates that a remote notification is available for the
app to process. The value of this key is an
NSDictionary containing the payload of the remote notification. See
the description of application:didReceiveRemoteNotification: for
further information about handling remote notifications.
Related
I am having action for login button in view controller but i have to use some condition in appdelegate.m that if user logged in already then viewcontroller login action method will fire and if not logged in then only login page will open?
Please help me
in AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([[NSUserDefaults standardUserDefaults]boolForKey:#"IsFirstTime"])
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle: nil];
HomePageVC *lvc = [storyboard instantiateViewControllerWithIdentifier:#"HomePageVC"];
[(UINavigationController *)self.window.rootViewController pushViewController:lvc animated:NO];
}
else
{
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:#"IsFirstTime"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
return YES;
}
in viewcontroller.m
- (IBAction)Login:(id)sender
{
[self.indicator startAnimating];//The ActivityIndicator Starts Animating Here
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl#"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"userName=gautam.kar#eyeforweb.com&userPassword=1234567&api_key=ZWZ3QDEyMw==&api_password=456789"];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString *text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"jsondic= %#",jsonDic);
NSDictionary *userDataDic = [jsonDic objectForKey:#"record"];
[DataModel setEmailAdd:[userDataDic objectForKey:#"emailAdd"]];
[DataModel setName:[userDataDic objectForKey:#"Name"]];
[DataModel setCity:[userDataDic objectForKey:#"city"]];
[DataModel setCountry:[userDataDic objectForKey:#"country"]];
[DataModel setRegistrationID:[userDataDic objectForKey:#"registrationID"]];
[DataModel setPhoneNo:[userDataDic objectForKey:#"phoneAdd"]];
[DataModel setState:[userDataDic objectForKey:#"state"]];
[DataModel settimeZone:[userDataDic objectForKey:#"timezone"]];
[DataModel setDisclaimer:[userDataDic objectForKey:#"disclaimer"]];
dispatch_async(dispatch_get_main_queue(), ^{
[self.indicator stopAnimating];//The ActivityIndicator Stops Animating when Response Arrives
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"text= %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
[self checkUserSuccessfulLogin:json];
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.indicator stopAnimating];
});
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
NSString *strID = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField1Text"];
NSString *strPWD = [[NSUserDefaults standardUserDefaults] stringForKey:#"textField2Text"];
[[NSUserDefaults standardUserDefaults] setValue:[dictionary objectForKey:#"user_id"] forKey:#"CurrentUserLoggedIn"];
NSString *strUser = [[NSUserDefaults standardUserDefaults] stringForKey:#"CurrentUserLoggedIn"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self saveLoginFileToDocDir:dictionary];
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
HomePageVC *vc = [mainStoryboard instantiateViewControllerWithIdentifier:#"HomePageVC"];
[self.navigationController pushViewController:vc animated:YES];
}
else
{
NSLog(#"Unsuccessful, Try again.");
UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];
}
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}
- (NSDictionary *)getLoginFileFromDocDir
{
NSArray*pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString*pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
return dict;
}
What you need is not to check your controller in AppDelegate.m, even though that is what you're asking.
Your real problem is " how can I access data from two different places ? ".
Right now, you're telling AppDelegate he "knows" your view controllers. It shouldn't.
What you need is one (actually a lot more but you'll learn that with time) new class, that handles the Login calls and state, and all that is login related.
Call that class the... LoginManager.
In that class, you could have some methods, like Login() or Logout(), or anything you would like.
Now you have an external source of data, your login manager knows everything he musts knows about the login. You should even add some properties, like a boolean IsLoggedIn or anything you might need.
And that source of data is what AppDelegate needs to know. Not the controllers. With that kind of architecture, EVERYONE that needs the login information can access it from that class (which could / should be a singleton class, look it up on the internet, its very easy.
In your viewcontroller, you can simply do Loginmanager.login, and in appdelegate, you can check .isloggedin.
That helps you a lot, because you don't have to instantiate view controllers in appdelegate, which is really a lot of work. You're splitting the work and the tasks between classes, which is what a good programmer does. Remember, your class should have only one job, not more, not less. Your VC handles the user inteface, not the webservic calls, not the login, nothing. If it does, it means you need to create another class :)
Once you've implemented all that (read my answer as many times as necessary to make sure you understand), you'll have no problem accessing that kind of data in other place of your app.
Note that you shouldn't abuse singleton classes or static classes (especially static), but again, you'll probably make many mistakes and learn from them, like we all did when we started.
Create your ViewController Object like below,
viewcontroller *objYourVC=[[viewcontroller alloc]init];
Now call method from Appdelegate like below:
[objYourVC functionToBeCalled:nil];
OR
[objYourVC functionToBeCalled:self];
Example,
if(AlreadyLogin){
//call viewcontroller method
viewcontroller *objYourVC=[[viewcontroller alloc]init];
[objYourVC functionToBeCalled:nil];
}
I already successfully integrated Google+ to my iOS app. But with the latest Apple store updates, the app is not allowed to open the browser to initiate the Google authentication using safari so i tried uiwebview for googleplus authentication and i am getting the access token but i cannot able to get the username and email address of the person logged in.Below i added my source,
NSString *client_id = #"***************************";;
NSString *secret = #"*******************************";
NSString *callbakc = #"https://www.example.com/oauth2callback";;
NSString *scope = #"https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.google.com/reader/api/0/subscription";
NSString *visibleactions = #"http://schemas.google.com/AddActivity";
#interface MainViewController ()
#end
#implementation MainViewController
#synthesize webview,isLogin,isReader;
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",client_id,callbakc,scope,visibleactions];
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// [indicator startAnimating];
NSLog(#"dgfduiussdiff %# ",[[request URL] host]);
if ([[[request URL] host] isEqualToString:#"www.example.com"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,client_id,secret,callbakc];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSError* error;
[receivedData appendData:data];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:receivedData
options:kNilOptions
error:&error];
NSLog(#"verifier %#",json);
}
- (void)connection:(NSURLConnection *)connection didFailWithError: (NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"%#", error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
SBJsonParser *jResponse = [[SBJsonParser alloc]init];
NSDictionary *tokenData = [jResponse objectWithString:response];
// WebServiceSocket *dconnection = [[WebServiceSocket alloc] init];
// dconnection.delegate = self;
NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#", [tokenData objectForKey:#"refresh_token"], self.isLogin];
// NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#",[tokenData accessToken.secret,self.isLogin];
// [dconnection fetch:1 withPostdata:pdata withGetData:#"" isSilent:NO];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Google Access TOken"
message:pdata
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
After executing the above source i getting the below response printed in nslog,
verifier 4/kMcSZ2l-d_XXPo24NSdsMnugoP_MGDGPP4D5C1LRTfY
2015-07-21 18:04:16.103 TechnoGerms.com[8981:189233] verifier {
"access_token" = "ya29.twG9kyMElyC8BgAxujF98WKN0BQ246Ey6zsKQEgSpKsNEb5JOS3QRl12La6XBy1geZnL";
"expires_in" = 3600;
"id_token" = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRhNjYyNWIzNmJjMDlkMzAwMzUzYjI4YTc0MWNlMTc1MjVhNGMzM2IifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE0MjE4NDEwODI0NzM1ODkyMDg0IiwiYXpwIjoiMTY5NzY2MjI4OTY4LWtoNzI1dTFpZWdzNHN1bnFhOThhcHUxMHU4djhhcmFmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhcmp1bkBsaW5rd2FyZS5pbiIsImF0X2hhc2giOiJQVnJxTURpNDViZnVGTm9kTmlsSFlRIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1ZCI6IjE2OTc2NjIyODk2OC1raDcyNXUxaWVnczRzdW5xYTk4YXB1MTB1OHY4YXJhZi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImhkIjoibGlua3dhcmUuaW4iLCJpYXQiOjE0Mzc0ODIwNTUsImV4cCI6MTQzNzQ4NTY1NX0.uSMrV8rOz4T4i5MhiCeQueNVGLv4NBLP-gtOcyow8t4BY9qvUO78sG4y0jPhbclPdX1kUZjzMVTeah2nU9fTYyl50dlj5FzWNy7LyM-a1GC2jEwkgWMgHdRPh6l7dqMrjQ9sU1rF-ZaiWfG7C9VJTJ76uEWRiSKKA9EFQtBil3xBtmDH07UMRxkbri2jBwaCPAWgjU8-dTarrxNESrwrO_nptaRzfGeaTyQBIYCAk6_9deXmblPgteER1OHoa65xb1OVK3ZPeZ3_dj9gjlXSyGp2ho5WIFGf2xRvW4XoROpUYqhLvrS3s-YrrZ8J5X5-3mafrs1qDjJYJogctbW7dg";
"token_type" = Bearer;
}
How i can get the username and email of person logged in by using the access token which i got above ? Please give any suggestions as i dont get any solution on google.
Thanks for your support
if you want to fetch the whole profile of the google+ user, you can use the below URL
https://www.googleapis.com/plus/v1/people/me/?access_token={YOUR_ACCESS_TOKEN}
Then call the GET method. You will be given by an array containing authorized profile details.
Another method is that, if you want to store the authorized users email, its already present in the field as id_token. It is a base64_encoded data with some fields. If you decode the id yo will get some information about the user.For example in your result you found id_token as
eyJhbGciOiJSUzI1NiIsImtpZCI6ImRhNjYyNWIzNmJjMDlkMzAwMzUzYjI4YTc0MWNlMTc1MjVhNGMzM2IifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE0MjE4NDEwODI0NzM1ODkyMDg0IiwiYXpwIjoiMTY5NzY2MjI4OTY4LWtoNzI1dTFpZWdzNHN1bnFhOThhcHUxMHU4djhhcmFmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhcmp1bkBsaW5rd2FyZS5pbiIsImF0X2hhc2giOiJQVnJxTURpNDViZnVGTm9kTmlsSFlRIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1ZCI6IjE2OTc2NjIyODk2OC1raDcyNXUxaWVnczRzdW5xYTk4YXB1MTB1OHY4YXJhZi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImhkIjoibGlua3dhcmUuaW4iLCJpYXQiOjE0Mzc0ODIwNTUsImV4cCI6MTQzNzQ4NTY1NX0.uSMrV8rOz4T4i5MhiCeQueNVGLv4NBLP-gtOcyow8t4BY9qvUO78sG4y0jPhbclPdX1kUZjzMVTeah2nU9fTYyl50dlj5FzWNy7LyM-a1GC2jEwkgWMgHdRPh6l7dqMrjQ9sU1rF-ZaiWfG7C9VJTJ76uEWRiSKKA9EFQtBil3xBtmDH07UMRxkbri2jBwaCPAWgjU8-dTarrxNESrwrO_nptaRzfGeaTyQBIYCAk6_9deXmblPgteER1OHoa65xb1OVK3ZPeZ3_dj9gjlXSyGp2ho5WIFGf2xRvW4XoROpUYqhLvrS3s-YrrZ8J5X5-3mafrs1qDjJYJogctbW7dg
The above id_token contains 2 parts separated by '.'. The first part is thebase64_encoded key and the second part is metadata.
you can decode both the data as
$key=base64_decode(eyJhbGciOiJSUzI1NiIsImtpZCI6ImRhNjYyNWIzNmJjMDlkMzAwMzUzYjI4YTc0MWNlMTc1MjVhNGMzM2IifQ)
will give you the key
$data=base64_decode(eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE0MjE4NDEwODI0NzM1ODkyMDg0IiwiYXpwIjoiMTY5NzY2MjI4OTY4LWtoNzI1dTFpZWdzNHN1bnFhOThhcHUxMHU4djhhcmFmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhcmp1bkBsaW5rd2FyZS5pbiIsImF0X2hhc2giOiJQVnJxTURpNDViZnVGTm9kTmlsSFlRIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1ZCI6IjE2OTc2NjIyODk2OC1raDcyNXUxaWVnczRzdW5xYTk4YXB1MTB1OHY4YXJhZi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImhkIjoibGlua3dhcmUuaW4iLCJpYXQiOjE0Mzc0ODIwNTUsImV4cCI6MTQzNzQ4NTY1NX0.uSMrV8rOz4T4i5MhiCeQueNVGLv4NBLP-gtOcyow8t4BY9qvUO78sG4y0jPhbclPdX1kUZjzMVTeah2nU9fTYyl50dlj5FzWNy7LyM-a1GC2jEwkgWMgHdRPh6l7dqMrjQ9sU1rF-ZaiWfG7C9VJTJ76uEWRiSKKA9EFQtBil3xBtmDH07UMRxkbri2jBwaCPAWgjU8-dTarrxNESrwrO_nptaRzfGeaTyQBIYCAk6_9deXmblPgteER1OHoa65xb1OVK3ZPeZ3_dj9gjlXSyGp2ho5WIFGf2xRvW4XoROpUYqhLvrS3s-YrrZ8J5X5-3mafrs1qDjJYJogctbW7dg)
will give you the metadata.
while decoding the data ,it will give the result as
{"iss":"accounts.google.com","sub":"114218410824735892084","azp":"169766228968-kh725u1iegs4sunqa98apu10u8v8araf.apps.googleusercontent.com","email":"arjun#linkware.in","at_hash":"PVrqMDi45bfuFNodNilHYQ","email_verified":true,"aud":"169766228968-kh725u1iegs4sunqa98apu10u8v8araf.apps.googleusercontent.com","hd":"linkware.in","iat":1437482055,"exp":1437485655}
Above result you can find the email filed. I hope this will help you.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a requirement that. I am using the Login screen in the app. The app shouldn’t even show the login screen once a user has logged in unless the user consciously logs out.
I am new to Objective-C. Can anyone please help me to do this.
Thanks in Advance.
This is my Login Button Code.I don't Know where to do that..
- (IBAction)LoginButton:(id)sender
{
#try
{
email = emailTextField.text;
password=passwordTextField.text;
NSLog(#"The email %# and Password is %# " , emailTextField.text,passwordTextField.text);
if ([ emailTextField.text isEqualToString:#""] || [passwordTextField.text isEqualToString:#""] )
{
UIAlertView *LoginAlert=[[UIAlertView alloc]initWithTitle:#"Fields Empty" message:#"Please Enter the your creadentials" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[LoginAlert show];
}
else
{
NSString *urlString =[NSString stringWithFormat:#"{\"Email\":\"%#\",\"Password\":\"%#\"}",emailTextField.text,passwordTextField.text];
NSLog(#"the post url %#",urlString);
NSString *post = urlString;
NSString *url=[NSString stringWithFormat:#"http://"];
NSLog(#"The whole url %# ", url);
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"", #""];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
NSLog(#"%#",authValue);
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSHTTPURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
id json = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:nil];
NSLog(#"json %# ", json);
if ([[json valueForKey:#"Status"] isEqualToString:#"Sucess"])
{
NSString *LoggedPersonID =[json valueForKey:#"PersonID"];
NSLog(#"the logged person ID is %#", LoggedPersonID);
[[NSUserDefaults standardUserDefaults] setObject:LoggedPersonID forKey:#"PersonIDUserDefaults"];
[[NSUserDefaults standardUserDefaults] synchronize];
//[self performSegueWithIdentifier:#"LoginSeque" sender:self];
[self CalculateWeekTwo];
if (_SecondJsonData != nil)
{
[self MyNotificationMethod];
[self performSegueWithIdentifier:#"LoginSeque" sender:self];
}
else
{
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:#"Error in Connection" message:#"Please check your network connectivity" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
else if ([[json valueForKey:#"Status"] isEqualToString:#"Error"] || json == nil)
{
UIAlertView *LoginAlert=[[UIAlertView alloc]initWithTitle:#"Login Failed" message:#"Please make sure you have entered the correct details" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[LoginAlert show];
}
}
//[[NSUserDefaults standardUserDefaults] setObject:#"10940" forKey:#"PersonIDUserDefaults"];
[[NSUserDefaults standardUserDefaults] synchronize];
//emailTextField.text=9416;
}
#catch (NSException *exception)
{
NSLog(#"exception %#", exception);
UIAlertView *alert =[[UIAlertView alloc]initWithTitle:#"Network Error" message:#"Please try later" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
#finally {
NSLog(#"what do i do here");
}
//[self performSegueWithIdentifier:#"LoginSeque" sender:self];
}
Use NSUserDefault modify your code like this.
[[NSUserDefaults standardUserDefaults] setObject:LoggedPersonID forKey:#"PersonIDUserDefaults"];//after this line add the below code
[[NSUserDefaults standardUserDefaults] setObject:#"YES" forKey:#"isLogIn"];//add this line in your given code
[[NSUserDefaults standardUserDefaults] synchronize];
Now you can add the code given below in application delegate if login is first screen or where ever you are calling your login screen.
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
if ([[defaults valueForKey:#"isLogIn"]isEqualToString:#"YES"]) {
//already login
//also you can access your LoggedPersonID here
}
else{
//call the login view here
}
You can also manage this without adding this isLogIn parameter.
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
if ([defaults valueForKey:#"PersonIDUserDefaults"]==nil) {
//call the login view here
}
else{
//logged in
}
- (IBAction)LoginButton:(id)sender
{
if ([[json valueForKey:#"Status"] isEqualToString:#"Sucess"])
{
// Navigate to login view controller
}
else
{
// Throw error alert
}
}
In my project I have achieved this by using NSCoding. Once user logs in he will remain logged in until he logged out and bypass the login screen.
For this I used two methods in my model class:
- (void) encodeWithCoder : (NSCoder *)encode ;
- (id) initWithCoder : (NSCoder *)decode;
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:_strDOB forKey:#"dob"];
[encoder encodeObject:_strEmail forKey:#"email"];
[encoder encodeObject:_strSName forKey:#"surname"];
}
- (id)initWithCoder:(NSCoder *)decoder{
if((self = [super init])){
_strDOB = [decoder decodeObjectForKey:#"dob"];
_strEmail = [decoder decodeObjectForKey:#"email"];
_strSName = [decoder decodeObjectForKey:#"surname"];
}
return self;
}
Than in your loginView.m:
- (void)saveObject:(Cls *)Obj key:(NSString *)key{
NSData *encodeObject = [NSKeyedArchiver archivedDataWithRootObject:Obj];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:encodeObject forKey:key];
[defaults synchronize];
}
- (Cls *)loadObjectWithKey:(NSString *)key{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *encodedObject = [defaults objectForKey:key];
Cls *Obj = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return Obj;
}
And finally in your login button method using
- (void)saveObject:(Cls *)Obj key:(NSString *)key;
method you can save your login credentials.
And in viewWillAppear method you need to call
- (Cls *)loadObjectWithKey:(NSString *)key;
method to load the object using NSUserDefault.
This will work surely it works for me.
Hope it help.
I have integrated google plus in my ios app ,I am able to get access token.I have used authentication flow to integrate google plus.So now after getting access token how can i get user profile details like username, email id, profile pic etc?
My code to get access token is as below:
-(IBAction)btnGooglePlusClicked:(UIButton *)sender
{
IBwebView.hidden = FALSE;
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CALL_BACK_URL,GOOGLE_PLUS_SCOPE,GOOGLE_PLUS_VISIBLE_ACTIONS];
[IBwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// [indicator startAnimating];
if ([[[request URL] host] isEqualToString:#"localhost"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CLIENT_SECRET,GOOGLE_PLUS_CALL_BACK_URL];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSLog(#"verifier %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"%#", error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
SBJsonParser *jResponse = [[SBJsonParser alloc]init];
NSDictionary *tokenData = [jResponse objectWithString:response];
// WebServiceSocket *dconnection = [[WebServiceSocket alloc] init];
// dconnection.delegate = self;
NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#", [tokenData objectForKey:#"refresh_token"], self.isLogin];
// NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#",[tokenData accessToken.secret,self.isLogin];
// [dconnection fetch:1 withPostdata:pdata withGetData:#"" isSilent:NO];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Google Access TOken"
message:pdata
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
I feel the the method you are using will not help to get the profile detail.
I suggest to use the proper method which ensures the best results.
Please check this out : https://developers.google.com/+/mobile/ios/
This will surely help you to get required outcome.
didFailLoadWithError being called only for iOS7.
This method is not called for iOS6.
The error logged is:
ERROR : Error Domain=NSURLErrorDomain Code=-999 "The operation
couldn’t be completed. (NSURLErrorDomain error -999.)"
UserInfo=0xcd0e200
{NSErrorFailingURLKey=bsp.gov.ph/statistics/sdds/exchrate.htm,
NSErrorFailingURLStringKey=bsp.gov.ph/statistics/sdds/exchrate.htm}
The error code -999 apparently is a URL Cancelled request but I am using the same code for iOS6 and works perfectly fine.
Why does it show an error for ios7?
The code I am using is:
- (void)viewDidLoad
{
[super viewDidLoad];
isFirstTime=TRUE;
ratesArray=[[NSArray alloc]initWithObjects:#"In",#"USD",#"JPY",#"GBP",#"HKD",#"CAD",#"SGD",#"AUD",#"SAR",#"THB",#"AED",#"CNY",#"KRW",#"EUR",#"MYR",#"TWD", nil];
NSLog(#"rates.count = %d",ratesArray.count);
defaults = [NSUserDefaults standardUserDefaults];
[self loadServerData];
}
-(void)loadServerData
{
GeneralClass *gen=[GeneralClass retrieveSingleton];
euroRatesArray =[[NSMutableArray alloc]init];
[euroRatesArray addObject:#"EURO"];
usRatesArray =[[NSMutableArray alloc]init];
[usRatesArray addObject:#"US"];
phpRatesArray =[[NSMutableArray alloc]init];
[phpRatesArray addObject:#"PHP"];
self.navigationController.navigationBar.hidden=TRUE;
if ([gen checkNetworkConnection] ) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//Create a URL object.
NSURL *url = [NSURL URLWithString:#"http://www.bsp.gov.ph/statistics/sdds/exchrate.htm"];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webPage loadRequest:requestObj];
} else {
defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:kExchanteRatesKey];
NSArray *contentArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
lblDate.text=[defaults objectForKey:kExchanteRateDate];
if (contentArray.count>0) {
for (int i=1; i<contentArray.count-1; i++) {
RateClass *rate=(RateClass *)[contentArray objectAtIndex:i];
[euroRatesArray addObject:(rate.text2.length>0 ? rate.text2:#"")];
[usRatesArray addObject:(rate.text3.length>0 ? rate.text3:#"")];
[phpRatesArray addObject:(rate.text4.length>0 ? rate.text4:#"")];
}
}
//NSLog(#"euroRatesArray = %#",euroRatesArray);
//NSLog(#"usRatesArray = %#",usRatesArray);
//NSLog(#"phpRatesArray = %#",phpRatesArray);
[activity setHidden:TRUE];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
[self hideActivityBar];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[self hideActivityBar];
}
-(void) hideActivityBar
{
[self htmlParse];
}
-(void)htmlParse
{
//NSString *html = [webPage stringByEvaluatingJavaScriptFromString: #"document.getElementById('exchrate_28426').innerHTML"];
//NSString *html = [webPage stringByEvaluatingJavaScriptFromString: #"document.getElementsByClassName('xl6528426')[0].innerHTML"];
NSString *html = [webPage stringByEvaluatingJavaScriptFromString:#"document.body.innerText"];
NSArray *array=[html componentsSeparatedByString:#"\n"];
NSLog(#"array.count = %d",array.count);
int checkRateIndex=1;
int index=212;
NSUserDefaults *standardUserDefaults=[NSUserDefaults standardUserDefaults];
}