Objective C write to Remote URL - objective-c

Ok, so I have the correct username / pass for a remote host, and I have a NSURL Object referring to the file on the server.
How can I possibly write data to that server via Objective-C? I cannot find anyone with this problem, so you help would be greatly appreciated!

I do it all the time with the program I am writing. The answer depends on what server you have installed and what languages it supports. If, as I think, you have PHP, just send a GET request to your server and instruct the PHP to write the data it receives.
This is a function of mine:
function checkInfo() {
$username = $_GET['username'];
$password = $_GET['password'];
connectToDataBase();
return returnSuccessObjectOn(isLoginInfoValid($username, $password));
}
On the client side:
NSURL *url = [NSURL URLWithString:kRequestLink];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:TIMEOUT];
OARequestParameter *reqCodeParameter = [[OARequestParameter alloc] initWithName:kParamReqCode value:[NSString stringWithFormat:#"%d",reqCode]];
[par addObject:reqCodeParameter];
[data enumerateKeysAndObjectsUsingBlock:composeRequestBlock];
[req setParameters:par];
NSLog(#"Sendind GET request: %#", [req description]);
activeConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
As you can see I use blocks

Related

AccessToken is not valid error : iOS Obj C

I am developing an iOS application in objective C where when a user logins to the App, it will return an access token in son format. I need to query other server api with the access token. My son response is like :
{
accessToken = "$2a$10$6Tu7e.fsKQxp4cw/SkRBS.65wsA.Pagt2EwdpBjXRdaUQb6yNxTtS";
id = 12;
message = "login successful";
success = 1;
}
I am retrieving this via
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[jsonDict valueForKey:#"accessToken"];
Whenever i try with the accessToken get from this, it shows invalid access token.(I use the same access token in postman.and got the same response).
When I copy the access token from postman and use the same in iOs code, it works fine. What is happening? Any help will be appreciated.
The code I am using to call the http request is:
// NSString *accessToken = [[NSUserDefaults standardUserDefaults] valueForKey:#"accessToken"];
//Send JSON data to cloud using HTTP POST
NSURL *url1 = [NSURL URLWithString:urlString];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url1
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request1 setHTTPMethod:#"GET"];
// [request1 setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 setValue:accessToken forHTTPHeaderField:#"Authorization"];
NSLog(#"access :: %#",accessToken);
NSURLConnection *conn1 = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];

oAuth2 retrieve profile email in iOS7

I followed this tutorial and was able to authenticate successfully and got the access token, now I am struggling to understand how can I get email associated with user profile before closing webview and join back my controller.
Any suggestions? I understand that Google has SDK for this, but I don't want to go that route if my requirement is possible with the tutorial I am using.
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!
}
//Should I need to call another HTTP to retrieve email (or) email already available part of any other response?
If I need to call another HTTP, what URL should be invoked?
Make an authenticated request to the people.get API method with the userId set to me. The person resource has an emails array and the email with type set to account is their verified email.

NSURLConnection not giving error with internet connection disabled?

Just wondering about this code below... when I turn off my internet connection and run it, I expected I would get "Connection failed" in my console log. Can anyone explain why I'm not? Thanks.
NSString *urlString = [NSString stringWithFormat:#"http://www.myurl.com/RSS/feed.xml"];
NSURL *serviceURL = [NSURL URLWithString:urlString];
//Create the request
NSURLRequest *request = [NSURLRequest requestWithURL:serviceURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
//Create the connection and send the request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//Make sure the connection is good
if (connection) {
//instantiate the responseData structure to store the response
self.responseData = [NSMutableData data];
}
else {
NSLog(#"Connection failed");
}
You haven't actually attempted to make the request yet. if (connection) doesn't test if the request was successful, it only tests whether or not you were able to create the object representing the connection. You still need to call one of the methods on it to make the request. See the documentation for details.
You're wanting to check to see if the connection itself failed, not the creation of the connection object, use the delegate, like so:
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog("Oh noes D=");
}

NSURLConnection doesn't send data, but connects

The URL is written properly, I tested it in the browser with data and it sends properly, but when I make the request, it returns that it is successful, but it does not actually write the data. Any idea?
- (void)writeAboutMe:(NSString *)about withIcebreaker:(NSString *)icebreaker
{
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *urlString = [NSString stringWithFormat:#"http://nailorbail.net63.net/submit_about_and_icebreaker.php?username=%#&about=%#&icebreaker=%#",[SignInViewController getUsernameString] ,about,icebreaker];
NSLog(#"%#",urlString);
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
NSLog(#"Connection Successful");
else
NSLog(#"Connection could not be made");
[conn release];
}
It could be an encoding issue. What kinds of characters are in getUsernameString, about, and icebreaker? As Maudicus mentioned, you need to handle special characters in the URL yourself.
Try:
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
You have set up an asynchronous connection. Do you implement the NSURLConnection delegate protocol methods? Are any of them being called?
The creation of the connection instance doesn't say anything about it's success.
Check out some tutorials, like this one.

Basic authorization in NSMutableURLRequest isn't working

I'm trying to add basic authorization to my request header. The code below compiles and I dont get any runtime errors. However, on the server side I do not see the "Authorization" in the header at all.
I was able to implement the didReceiveAuthenticationChallenge method and that works, but I dont understand why I have to do it this way. I simply want to always add basic auth to every request.
I'm not interested in using ASIHTTPRequest.
Thanks for the help!
This is my code below:
NSURL *url = [[NSURL alloc] initWithString:#"http://localhost:8000/MyWebService"];
self.userName = #"myusername";
self.password = #"mypassword";
NSMutableString *credentials = [[NSMutableString alloc] initWithFormat:#"%#:%#", userName, password];
NSString *encodedCredentials = [[credentials dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSString *authHeader = [NSString stringWithFormat:#"Basic %#", encodedCredentials];
NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
[req addValue:authHeader forHTTPHeaderField:#"Authorization"];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
if (self.urlConnection) {
self.receivedData = [NSMutableData data];
}
else {
errorLabel.text = #"Error connecting to the server";
}
The didReceiveAuthenticationChallenge is the way it works in iOS and the easiest way to do it. It will be submitted with every request (with the challenge). Guess that's not what you want to hear=)
I guess you have tried using different tutorials. I've used this one to authenticate before:
Basic access Auth, iOS