Logging in from settings username and password preferences - ios

I have an app that uses webView. In the home screen of a website I want to login using username and password entered by the user in the app's settings option. Currently I have this code which I saw in solution to a similar question asked on this forum. But it isn't working (neither it did for the other guy).
-(IBAction)cachepressed:(id)sender{
NSString *baseurl=[[NSUserDefaults standardUserDefaults] stringForKey:#"url_preference"];
NSString *username= [[NSUserDefaults standardUserDefaults] stringForKey:#"name_preference"];
NSString *password= [[NSUserDefaults standardUserDefaults] stringForKey:#"pswrd_preference"];
NSString* content = [NSString stringWithFormat:#"username=%#&password=%#", username, password];
NSData *data=[content dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postlength=[NSString stringWithFormat:#"%d",[data length]];
NSString *loginpage= [baseurl stringByAppendingString:#"/index.php?title=Special:UserLogin"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:loginpage]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:data];
NSError *error=nil;
NSURLResponse *response=nil;
NSData *result=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *HTMLString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
[webView loadHTMLString:HTMLString baseURL:[NSURL URLWithString:loginpage]];
}
I am not too sure about the two lines of code starting with [request setValue...]. Can somebody suggest a solution to this? It would be a great help. Thanks in anticipation.

This depends a lot on how the authentication is done on the website.
Based on what I can figure from your question, the code you posted sends values for the fields named "username" and "password" to the index.php?title=Special:UserLogin page using POST.
You need to make sure that everything is set accordingly.
1. Are your fields name the same on the website?
Maybe the login form uses different field names, not username and password. Check the source code and see if the input names are indeed "username" and "password"
2. Does your host allow posting data from a different source?
I used to set mine so no POST request would work if they didn't originate from my server, so POSTing data from an iPad would not have functioned.
Is this the case for you too?
3. The login process is really done by posting data to that page?
Maybe on the website the authentication is done using AJAX on a different php page and then you get redirected to index.php?title=Special:UserLogin, I've seen such cases in the past.
Bottom line is that you need to know exactly how the login is done on the website before doing it inside a webview. Correct me if I'm wrong, but based on your post it doesn't seem to be the case here

Related

IOS unable to insert data in to mysql database

Hello everyone I am trying to insert my user data in myaql database using JSON. But i am unable to do so, data is not inserting and getting no error. following is my code.
Objective C Code
{
NSString *post =[NSString stringWithFormat:#"name=%#&email=%#&password= %#&phone=%#",self.name.text, self.Pass.text,self.phone.text,self.email.text];
NSData *data = [post dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"http://my url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
}
I am using this code to insert textfields data into my mysql database.It seems no error but data is not inserting in my database. Thanks in Advance.
Your first line itself doesn't seem true:
NSString *post =[NSString stringWithFormat:#"name=%#&email=%#&password= %#&phone=%#",
self.name.text, self.Pass.text,self.phone.text,self.email.text];
Do you require space " " after text "password="
In formation the sequence is: name, email, password, phone, but in parameter list phone is at third place and email at last.
It should be:
NSString *post =[NSString stringWithFormat:#"name=%#&email=%#&password=%#&phone=%#",
self.name.text, self.email.text,self.Pass.text,self.phone.text];
I guess that's causing issue, it might be in datatype mismatch with database table schema, for phone column (numbers) to email column (characters).
Seems like your iOS implementation is correct, but your server side is not.
You could try the following:
In your Server-side script, where your MySQL insert-statement is being generated, just do a
echo $insertScript;
and then run your App again and see what the response says. It should return a valid MySQL insert script. Copy it and run it on your server's mysql instance and see what happens
Also, remove those spaces in your password field

How to connect to EC2 instance within an iOS App

I have an AWS EC2 instance and an app that I created. The app is for people who get migraines (tracks info, tells them what their trigger(s) are). Now I want to be able to send user input from my application to a server so that I can see trends. I am having difficulty connecting to the server and finding out how I would be able to write files to the server.
I have written this method:
- (void) sendDataToServer:(NSString *)url :(NSString *)key : (NSString *) content{
// define your form fields here:
//NSString *content = #"field1=42&field2=Hello";
NSString *address = [NSString stringWithFormat:#"ssh -i %# %#", key, url];
NSLog(#"%#", address);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:address]];
[request setHTTPMethod:#"POST"];
NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:contentData];
NSString *postLength = [NSString stringWithFormat:#"%d",[contentData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// generates an autoreleased NSURLConnection
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn){
NSLog(#"connection");
}
//[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//[self doSomethingWithData:data];
if (error){
NSLog(#"ERROR");
}
}];
}
I put the private key from my key pair into the app. How would I use that to connect? Should I not be using my private key? Should I be doing this differently?
Should I be doing this differently?
Absolutely, 100%, YES. You don't want to let people SSH into your server, especially by embedding your private key into an app binary. It's crazy easy for someone to get it, then wreak havoc upon your server.
Don't do this.
Instead, I would get a web server like Apache running on your instance (it's trivial), and write an application (in PHP, Rails (with Passenger), Python, whatever) that saves files to the server's hard drive. You'll also want to get an Elastic IP address so that it stays constant, as ashack mentioned.
In your iOS app, you'll want to send a POST request to your server. See Sending an HTTP POST request on iOS, it's essentially what you're doing now.
Don't publish your private SSH key. It's private for a good reason.

Fetching an access token for youtube api iOS "Error" : "invalid_request"

I'm trying to get an access token for a youtube app for iOS. Here's the relevant code I have been using from my viewDidLoad method:
mAuth = [[GTMOAuth2Authentication alloc]init];
[mAuth setClientID:#"<MY CLIENT ID>"];
[mAuth setClientSecret:#"<MY CLIENT SECRET>"];
[mAuth setRedirectURI:#"urn:ietf:wg:oauth:2.0:oob"];
[mAuth setScope:#"https://gdata.youtube.com"];
[self.web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?client_id=%#&redirect_uri=%#&scope=%#&response_type=code&access_type=offline", mAuth.clientID, mAuth.redirectURI, mAuth.scope]]]];
After this is called, the user has to grant access to their account, then I retrieve the auth code from the resulting page in the following code:
NSString *string = [self.web stringByEvaluatingJavaScriptFromString:#"document.title"];
if([string rangeOfString:#"Success"].location != NSNotFound){
NSLog(#"This is the code page");
NSString *importantCode = [[string componentsSeparatedByString:#"="] objectAtIndex:1];
NSLog(#"%#", importantCode);
if([self.defaults objectForKey:#"super important code"] == nil){
[self.defaults setObject:importantCode forKey:#"super important code"];
[self.defaults synchronize];
NSString *post = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=code", [self.defaults objectForKey:#"super important code"], mAuth.clientID, mAuth.clientSecret, mAuth.redirectURI];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"]]];
[request setHTTPMethod:#"POST"]; [request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[self.web loadRequest:request];
}
[timer invalidate];
}
After that, I should be given the access token in response to my POST request, but instead I get a page that simply says:
{
"error" : "invalid_request"
}
Does anyone (see where I went wrong)/(know how to retrieve the access token)?
I’d be interested in knowing what the HTTP status code is... I suspect ”invalid_request” means 400, which almost always means there’s some irritating stupid little error in the way you composed your authent URI. I don’t know enough iOS/ObcJ to tell if you’ve properly URLescaped any funny characters in any of the parameter values, but it’s worth checking. Or a typo in one of the values, or an extra newline creeping in or something?
It was as simple as this, I had set the grant_type parameter to 'code' when it should have been 'authorisation_code' if you are reading this and you are using the youtube api, don't make the same mistake. If you're reading this and you're sending a POST request in general, this error "invalid_request" means that either you skipped one of the parameters you should have added, or you added it incorrectly.

How do I create a post for Disqus from iOS?

I'm developing an application for a client. This app enables user to read and post comment. Our client website have already used Discus. Now that we can retrieve the comment and display it natively. But we find no way to create a post and send it to Disqus. Does anyone have some experiences with Disqus on iOS ?
Any idea will be much appreciated.
Edit : our client website has an authentication system already and thus we also integrate that system to our app. Every time user post a comment in the app, we'll use his/her authentication information. We don't want user to authenticate again.
Here is a great solution which helps easily integrate Disqus into iOS apps https://github.com/moqod/disqus-ios. Works like a charm out of the box.
Not only you can make posts, but also authorize thru social networks and respond to comments.
You have the API set up on your server, correct? Then post a request to your server, pass it whatever API keys and credentials you need, and have the server make a post to the Disqus API on behalf of the client. Basically, build your own iOS API for interfacing with the Disqus API through your server.
Even better though would be to directly interact with the Disqus server by making requests using NSURLRequest/Connection. For more information on Disqus requests look here. That would make your app faster and be less error prone, unless you are doing some critical activity on your server, other than just posting and displaying comments.
#RahuGupta: Sorry if it's too late for a response. I posted comment using SSO, I don't know about posting as guest. But it should be easier.
In my case I post a comment using third party authentication server which means we authenticate users by ourselves. The technique called SSO. You may want to read the documentation about SSO on Disqus.
In case you need code snippet in objective-c :
NSMutableDictionary *dico = [[NSMutableDictionary alloc] init];
[dico setValue:[NSString stringWithFormat:#"uniqueId_%#",comment.authorID] forKey:#"id"];
[dico setValue:comment.authorName forKey:#"username"];
[dico setValue:comment.authorEmail forKey:#"email"];
NSString *message = [dico JSONRepresentation];
NSString *message64Based = [DataPost base64String:message];
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
NSString *secret = DISQUS_API_SECRET;
NSString *api_key = DISQUS_API_PUBLIC;
//comment.threadID will makes the app crashed, because when comment is not fully loaded, it's nil
NSString *threadID = [NSString stringWithFormat:#"%#",comment.threadID];
NSString *commentMessage = [[comment.rawMessage stringByReplacingOccurrencesOfString:#"=" withString:#"%3D"] stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSString *host = #"http://example.com";
NSString *referrer = #"example.com";
NSString *hmac = [self hashedValue:secret andData:[NSString stringWithFormat:#"%# %.0lf",message64Based, timeStamp]];
NSString *remote_auth_s3 = [[[NSString stringWithFormat:#"%# %# %.0lf", message64Based, hmac, timeStamp] stringByReplacingOccurrencesOfString:#"=" withString:#"%3D"] stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSMutableURLRequest *uploadRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://disqus.com/api/3.0/posts/create.json"] cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 60.0f];
NSMutableData *postData = (NSMutableData *)[[NSString stringWithFormat:#"_format=json&thread=%#&message=%#&remote_auth=%#&api_key=%#&strict=1", threadID , commentMessage, remote_auth_s3 , api_key] dataUsingEncoding:NSUTF8StringEncoding];
[uploadRequest setHTTPMethod:#"POST"];
[uploadRequest setHTTPBody: postData];
[uploadRequest setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[uploadRequest setValue:referrer forHTTPHeaderField:#"referrer"];
[uploadRequest setValue:host forHTTPHeaderField:#"host"];
[uploadRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSHTTPURLResponse *response=nil;
NSError *error = nil;
[NSURLConnection sendSynchronousRequest:uploadRequest returningResponse:&response error:&error];

How to upload images in a scrollview onto a web server?

I have an iOS app that has a series of images in a scrollview (camera pictures). I want to be able to post these on to a url individually or collectively as a group.
Can someone point me to an example or some sample code that would get me started?
Much appreciated
in that case if you if you set up your server (how do this i don`t now, because i used quickblox - ready-made solution) try send GET-request to the server. You can try this like this:
(source - How to send a Get request in iOS? )
NSString *getString = [NSString stringWithFormat:#"parameter=%#",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getLength = [NSString stringWithFormat:#"%d", [getData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https:yoururl"]];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:getData];
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSAssert(self.urlConnection != nil, #"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
For more advanced preferences I would advise you try learn http://allseeing-i.com/ASIHTTPRequest/
For this you can create file server or use other maded. Look this: http://quickblox.com/ - they has blobs and ios api for their server, so download|upload files simple implemented in code.
First, you need register your account and then register your app.( https://admin.quickblox.com/signin ) (it's not difficult, few minuts)
Then, using instructions from site added Quickblox auth to your app and then use QBBlobs for dowload photo. Good luck!

Resources