ios - How to get access token from Google,Yahoo? - iphone

I'm new to iPhone development,I'm trying to get access token,I have to complete that task in time.I got this link http://www.stevesaxon.me/posts/2011/window-external-notify-in-ios-uiwebview/ to do that,but I couldn't able to understand clearly.Can anyone help me?
How to call the given javascript properly in below code?
<script type='text/javascript'>\
window.external =\
{\
'Notify': function(s) { document.location = 'acs://settoken?token=' + s; },\
'notify': function(s) { document.location = 'acs://settoken?token=' + s; }\
}\
</script>
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(_data)
{
NSString* content = [[NSString alloc] initWithData:_data
encoding:NSUTF8StringEncoding];
[_data release];
_data = nil;
NSString* jsString = #"<script type='text/javascript'>\
window.external =\
{\
'Notify': function(s) { document.location = 'acs://settoken?token=' + s; },\
'notify': function(s) { document.location = 'acs://settoken?token=' + s; }\
}\
</script>";
NSString *result = [webView stringByEvaluatingJavaScriptFromString: jsString];
content = [content stringByAppendingString:result];
[webView loadHTMLString:content baseURL:_url];
}
}
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
if(_url)
{
if([_url isEqual:[request URL]])
{
return YES;
}
[_url release];
}
//Here am getting http://LoginSuccess.aspx
_url = [[request URL] retain];
NSString* scheme = [_url scheme];//Here am getting http
//So here condition fails
if([scheme isEqualToString:#"acs"])
{
// parse the JSON URL parameter into a dictionary
_url = [NSURL URLWithString:#"https://converse.accesscontrol.windows"];
NSDictionary* pairs = [self parsePairs:[_url absoluteString]];
if(pairs)
{
WACloudAccessToken* accessToken;
accessToken = [[WACloudAccessToken alloc] initWithDictionary:pairs];
//[WACloudAccessControlClient settoken:accessToken];
[self dismissModalViewControllerAnimated:YES];
}
return NO;
}
[NSURLConnection connectionWithRequest:request delegate:self];
return NO;
}
Any ideas? Thanks in advance.

Try this :-
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(_data)
{
NSString* content = [[NSString alloc] initWithData:_data
encoding:NSUTF8StringEncoding];
[_data release];
_data = nil;
NSString* Html = #" <script type='text/javascript'>\
window.external =\
{\
'Notify': function(s) { document.location = 'acs://settoken?token=' + s; },\
'notify': function(s) { document.location = 'acs://settoken?token=' + s; }\
}\
</script>";
//Here to call that javascript
NSString *result = [_webView stringByEvaluatingJavaScriptFromString:Html];
content = [ScriptNotify stringByAppendingString:result];
[webView loadHTMLString:content baseURL:_url];
}
}

Related

Get error -:: {"error":{"message":"Bad signature","type":"OAuthException","code":1}}

I Get the access token from the following
if ([FriendPeekerAppDelegate sharedDelegate].session.isOpen)
{
}
else
{
[FriendPeekerAppDelegate sharedDelegate].session = [[FBSession alloc] init];
[[FriendPeekerAppDelegate sharedDelegate].session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error)
{
// and here we make sure to update our UX according to the new session state
[self updateView];
}];
- (void)updateView
{
if ([FriendPeekerAppDelegate sharedDelegate].session.isOpen)
{
accessToken = [NSString stringWithFormat:#"https://graph.facebook.com/me/friends?access_token=%#",
[FriendPeekerAppDelegate sharedDelegate].session.accessTokenData.accessToken];
if (accessToken != nil)
{
self.accessToken = accessToken;
}
if ( (callbackObject != nil) && (callbackSelector != nil) )
{
[callbackObject performSelector:callbackSelector];
}
}
else
{
}
}
and then i want response for
-(void)getMyInfo
{
FbGraphResponse *fb_graph_response = [self.fbGraph doGraphGet:#"me" withGetVars:nil];
NSString *tempStr = (NSString *)[fb_graph_response.htmlResponse retain];
id dict = [[CheckConnectionAndJsonParing singleton]jsonToFoundationRepresentation:tempStr];
}
- (FbGraphResponse *)doGraphGet:(NSString *)action withGetVars:(NSDictionary *)get_vars {
NSString *url_string = [NSString stringWithFormat:#"https://graph.facebook.com/%#?", action];
//tack on any get vars we have...
if ( (get_vars != nil) && ([get_vars count] > 0) ) {
NSEnumerator *enumerator = [get_vars keyEnumerator];
NSString *key;
NSString *value;
while ((key = (NSString *)[enumerator nextObject])) {
value = (NSString *)[get_vars objectForKey:key];
url_string = [NSString stringWithFormat:#"%#%#=%#&", url_string, key, value];
}//end while
}//end if
if (accessToken != nil) {
//now that any variables have been appended, let's attach the access token....
url_string = [NSString stringWithFormat:#"%#access_token=%#", url_string, self.accessToken];
}
//encode the string
url_string = [url_string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return [self doGraphGetWithUrlString:url_string];
}
- (FbGraphResponse *)doGraphGetWithUrlString:(NSString *)url_string {
FbGraphResponse *return_value = [[[FbGraphResponse alloc] init] autorelease];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url_string]];
NSError *err;
NSURLResponse *resp;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];
if (resp != nil) {
/**
* In the case we request a picture (avatar) the Graph API will return to us the actual image
* bits versus a url to the image.....
**/
if ([resp.MIMEType isEqualToString:#"image/jpeg"]) {
UIImage *image = [UIImage imageWithData:response];
return_value.imageResponse = image;
} else {
NSString *stringResponse = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
return_value.htmlResponse = stringResponse;
[stringResponse release];
}
} else if (err != nil) {
return_value.error = err;
}
return return_value;
}
please sugggest me .......
Looks like the answer to your problem lies within Facebook. Here's a question that should help:
Why is the echo tool saying bad signature?

ios - How to append javascript with HTML content?

I'm trying to get access token,I'm following this link to get that,but some condition fails,I think am not properly append the javascript with HTML content.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(_data)
{
NSString* content = [[NSString alloc] initWithData:_data
encoding:NSUTF8StringEncoding];
[_data release];
_data = nil;
NSString *jsString = #"<script type='text/javascript'>\
window.external =\
{\
'Notify': function(s) { document.location = 'acs://settoken?token=' + s; },\
'notify': function(s) { document.location = 'acs://settoken?token=' + s; }\
}\
</script>";
content = [jsString stringByAppendingString:content];
[webView loadHTMLString:content baseURL:_url];
}
}
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
if(_url)
{
if([_url isEqual:[request URL]])
{
return YES;
}
[_url release];
}
//Here am getting http://LoginSuccess.aspx
_url = [[request URL] retain];
NSString* scheme = [_url scheme];//Here am getting http
//So here condition fails
if([scheme isEqualToString:#"acs"])
{
// parse the JSON URL parameter into a dictionary
_url = [NSURL URLWithString:#"https://converse.accesscontrol.windows"];
NSDictionary* pairs = [self parsePairs:[_url absoluteString]];
if(pairs)
{
WACloudAccessToken* accessToken;
accessToken = [[WACloudAccessToken alloc] initWithDictionary:pairs];
//[WACloudAccessControlClient settoken:accessToken];
[self dismissModalViewControllerAnimated:YES];
}
return NO;
}
[NSURLConnection connectionWithRequest:request delegate:self];
return NO;
}
Any ideas? Thanks in advance.
I´m not sure if i unterstand exactly what you´re trying to do, but I assume
[UIWebView stringByEvaluatingJavaScriptFromString:#"yourJavaString"];
could help. I use it to perform an JavaScript based Loginmechanism in one of my projects.
See the Apple doc here .
You have to use stringByEvaluatingJavaScriptFromString AFTER WebView has loaded.

how to go to another ViewController after successful login

I am newbie for iPhone application. I have followed this tutorial for login from iPhone.
I have php file as below.
index.php
<?php
$user = $_POST['uname'];
if ($user == 'user') {
echo "Welcome to my site...";
} else {
echo "Invalid User";
}
?>
When I run application and enter username as user and password as some text, I get output as Welcome to my site....
Now instead of welcome message, I wanna go to my welcome screen i.e. View Controller that I have on story board. Any idea how to get this done?
Full code is as below.
-(IBAction)buttonClick:(id)sender
{
greeting.text= #"";
NSString* username = nameInput.text;
NSString* pass = passInput.text;
greeting.hidden = NO;
if([nameInput.text isEqualToString:#"" ] && [passInput.text isEqualToString:#""])
{
greeting.text = #"Please enter username and password.";
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
return;
}
if([nameInput.text isEqualToString:#"" ])
{
greeting.text = #"Please enter username.";
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
return;
}
if([passInput.text isEqualToString:#""])
{
greeting.text = #"Please enter password.";
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
return;
}
NSString *post = [[NSString alloc] initWithFormat:#"uname=%#&pwd=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://localhost:8888/PhPTesting/index.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
indicator.hidden = NO;
webData = [[NSMutableData data] retain];
}
else
{
}
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
nameInput.text = nil;
passInput.text = nil;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
indicator.hidden = YES;
}
You can do this :
if ([loginStatus isEqualToString:#"Welcome to my site..."]) {
// Show welcome view controller
NextViewController *nextViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"myNextView"];
[self.navigationController pushViewController:nextViewController animated:YES];
} else {
greeting.text = #"Login was not correct";
}
Here , #"myNextView" is a NextView Identifier.
You can check the result
if ([loginStatus isEqualToString:#"Welcome to my site..."]) {
// Show welcome view controller
} else {
greeting.text = #"Login was not correct";
}
I also suggest returning a more helpful string via PHP
UPDATE
There are tons of tutorials for presenting a new view.
Check out this here: Programatically Switching Views in Cocoa Touch

iPhone - NSURLConnection asynchronous download using URLs in NSArray

I have seen almost all the posts about NSURL on this site, and I am still stuck. I am using Xcode 4.5.
I am trying to download images and display them in a UIScrollView.
I want to download asynchronously download images using URLs, that get stored in an array populated using JSON. I get the URLs from a JSON grab off of my database. That works quite well and I can see the URL's being placed into the urlArray, but making the URLConnection to get the image, seems to fail.
I can't get any of the images to download, or at least they don't show up in my imageArray.
Here is my code and thank you for any help!! Let me know what else is needed
- (void)viewDidLoad
{
[super viewDidLoad];
//show network activity to user.... very useful
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//call getJSON. getJSON does not parse, but it connects and gets the data.
[self getJSON];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)getJSON
{
NSURL *url = [NSURL URLWithString:#"http://"My server goes here/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//just initialize the connection, do not
[[NSURLConnection alloc] initWithRequest:request delegate:self]; //"Ecression result unused" warning here
}
- (void)getNextImage
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
for (int y = 0; y < urlArray.count; y++)
{
NSString *urlString = [urlArray objectAtIndex:y];
NSLog(#"Array String is: %# ", urlString);
NSURL *arrayURL = [NSURL URLWithString:urlString];
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:arrayURL];
NSData *imgData = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self]; //"Incompatible pointer types initializing ..." warning here
imageData = [UIImage imageWithData:imgData];
[imageArray addObject:imageData];
}
NSLog(#"LEAVING getNextImage");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
theJsonData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[theJsonData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
urlArray = [[NSMutableArray alloc] init];
//This is where all the JSON Parsing is being done.
//Turn off the data indicator, because the download is complete.
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
jsonArray = [NSJSONSerialization JSONObjectWithData:theJsonData options:nil error:nil]; //"Incompatible pointer types initializing ..." warning here
//get the URL strings out of the jsonArray
for (int x = 0; x < jsonArray.count; x++)
{
NSString *urlString = [[jsonArray objectAtIndex:x] objectForKey:#"image_URL"];
NSLog(#"String is %# ", urlString);
[urlArray addObject:urlString];
}
[self getNextImage];
//display the images..... Not sure why this is in connectionDidFinishLoading.
for (int x = 0; x < imageArray.count; x++)
{
CGRect frame;
frame.origin.x = self.mainScroll.frame.size.width * x;
frame.origin.y = 0;
frame.size = self.mainScroll.frame.size;
UIImageView *nextIV = [[UIImageView alloc] initWithFrame:frame];
[nextIV setImage:imageData];
[self.mainScroll addSubview:nextIV];
//NSLog(#"Pass %d", x);
}
self.mainScroll.contentSize = CGSizeMake(self.mainScroll.frame.size.width * imageArray.count,1.0);
NSLog(#"!!!!!!leaving connection did finnish loading!!!!!");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//show error message to user if there is a connection error.
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The Download could not complete - please make sure you're connected to the internet." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
//turn off the network activity indicatior
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
you never download imageData. you assign it the request object . thats why you get the warning too. a NSURLConnection object is not a NSData object: NSData *imgData = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self]; //"Incompatible pointer types initializing ..." warning here
I would today rewrite it using the startAsyncConnection method. sec
-- there you go, untested and written in text edit but it should get you started (I reused most of your code but cut it down a lot too)
#import "RootViewController.h"
#interface RootViewController ()
#property(assign) IBOutlet UIScrollView *mainScroll;
#end
#implementation RootViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self getJSONAndImageData];
}
- (void)getJSONAndImageData
{
NSURL *url = [NSURL URLWithString:#"http://My server goes here/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse*r, NSData*d, NSError*e) {
[self parseJSONAndGetImages:d];
}];
}
- (void)parseJSONAndGetImages:(NSData*)data
{
NSMutableArray *urlArray = [[NSMutableArray alloc] init];
//This is where all the JSON Parsing is being done.
//Turn off the data indicator, because the download is complete.
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *jsonArray = (NSArray*)[NSJSONSerialization JSONObjectWithData:data options:nil error:nil]; //"Incompatible pointer types initializing ..." warning here => likely not an array then
assert([jsonArray isKindOfClass:[NSArray class]]);
//could be made in one liner with KVC
//get the URL strings out of the jsonArray
for (int x = 0; x < jsonArray.count; x++)
{
NSString *urlString = [[jsonArray objectAtIndex:x] objectForKey:#"image_URL"];
NSLog(#"String is %# ", urlString);
[urlArray addObject:urlString];
}
[self loadImageArray:urlArray handler:^(NSArray* imageArray) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
for (int x = 0; x < imageArray.count; x++)
{
CGRect frame;
frame.origin.x = self.mainScroll.frame.size.width * x;
frame.origin.y = 0;
frame.size = self.mainScroll.frame.size;
UIImageView *nextIV = [[UIImageView alloc] initWithFrame:frame];
[nextIV setImage:imageArray[x]];
[self.mainScroll addSubview:nextIV];
//NSLog(#"Pass %d", x);
}
self.mainScroll.contentSize = CGSizeMake(self.mainScroll.frame.size.width * imageArray.count,1.0);
}];
}
//for SIMPLICITY I do synchronous networking here!
- (void)loadImageArray:(NSArray *)urlArray handler:(void(^)())handler {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSMutableArray *imageArray = [NSMutableArray array];
for (int y = 0; y < urlArray.count; y++)
{
NSString *urlString = [urlArray objectAtIndex:y];
NSLog(#"Array String is: %# ", urlString);
NSURL *arrayURL = [NSURL URLWithString:urlString];
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:arrayURL];
NSData *imgData = [NSURLConnection sendSynchronousRequest:imageRequest returningResponse:nil error:nil];
UIImage *image = [UIImage imageWithData:imgData];
[imageArray addObject:image];
}
dispatch_async(dispatch_get_main_queue(),^ {
handler(imageArray);
});
});
}
#end

IPHONE SDK : NSURLConnection asynchronous / wait completion bug ?

I am trying to use NSURLConnection in asynchronous mode and wait for completion.
During the wait, I use NSRUNLOOP to handle events. Its works in most cases (3G and WIFI)
but the application hangup randomly in GSM DATA and EDGE environment.
My code:
(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
_requestCompleted = TRUE;
CFRunLoopStop(CFRunLoopGetCurrent());
}
(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_response = (NSHTTPURLResponse *)response;
[ _response retain];
}
(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
/* Append the new data to the received data. */
[_receivedData appendData:data];
}
(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
_requestError = error;
NSLog(#"request error - cause : %#", [_requestError localizedDescription ]);
_requestCompleted = TRUE;
[_requestError retain];
CFRunLoopStop(CFRunLoopGetCurrent());
}
(NSString*)downloadFileFromURL:(NSString*)url
{
NSURLRequest *request = nil;
NSString *contents = nil;
NSData *response = nil;
int tries;
NSURLConnection *URLConnection = nil;
int i = 0;
NSDate* dateLimit;
[_mutex lock];
NSLog(#"url = %#", url);
NSString *requestWithEscaping = [ url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestWithEscaping]
cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:30];
for (tries = 0; tries < HTTP_REQUESTS_TRIES && response == nil ; tries ++) {
[_receivedData setLength:0];
_requestCompleted = FALSE;
_requestError = nil;
_requestTimeout = FALSE;
if (URLConnection == nil)
URLConnection = [ NSURLConnection connectionWithRequest:request delegate:self];
else {
[URLConnection cancel ];
[URLConnection start];
}
if (URLConnection == nil) {
NSLog(#"No connection ! maybe mistake in Request Format ?");
continue;
}
for (i = 0; ; i++) {
dateLimit = [[NSDate date] addTimeInterval:INTERVALL_LOOP];
[ [NSRunLoop currentRunLoop] runUntilDate:dateLimit];
if (_requestCompleted == TRUE)
break;
if (i > (int)(HTTP_TIMEOUT_FIRE * (1 / INTERVALL_LOOP))) {
_requestTimeout = TRUE;
break;
}
}
if (_requestTimeout) {
[ URLConnection cancel];
NSLog(#"request timeout");
continue;
}
if (_requestError) {
NSLog(#"request error");
continue;
}
NSLog(#"Request success");
break;
}
if (_requestTimeout) {
_lastErrorType = ServicesRequestManager_error_Network;
[ _lastErrorString setString:#"Délai de connexion depassé"];
[ _mutex unlock];
return nil;
}
if (_requestError) {
NSLog(#"ERROR Cannot get %# - cause : %#",url, [ _requestError localizedDescription ]);
_lastErrorType = ServicesRequestManager_error_Network;
[_lastErrorString setString:#"Impossible de se connecter" ];
[ _mutex unlock];
return nil;
}
if ([ _response statusCode] != 200 ) {
NSLog(#"ERROR Download file %# HTTP response - code : %d", url, [ _response statusCode]);
[_lastErrorString setString:[ NSString stringWithFormat:#"Error http code : %d", [_response statusCode]]];
_lastErrorType = ServicesRequestManager_error_Service;
[_lastErrorString setString:#"Le service n'est pas disponible actuellement" ];
[ _mutex unlock];
return nil;
}
contents = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
[ _mutex unlock];
return contents;
}
NSURLConnection is already asynchronous. Simply implement the delegate methods. If you want to update the UI on the MainThread (e.g. a progress bar), you can do so in didReceiveData.
I use NSNotificationor that puspose. In DidFinishLoading method post a notification,
[[NSNotificationCenter defaultCenter] postNotificationName:#"Name" object:someObject];
and handle this notification in anyclass by
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleMethod:) notificationName:#"Name" object:nil];
and implement
-(void)handleMethod:(NSNotification *)ntf