I am trying to achieve the following in Objective-C:
curl -X POST -u "<application key>:<master secret>" \
-H "Content-Type: application/json" \
--data '{"aps": {"badge": 1, "alert": "The quick brown fox jumps over the lazy dog."}, "aliases": ["12345"]}' \
https://go.urbanairship.com/api/push/
Is there some sort of library I can use that achieves this? Obviously I have all of the values ready to go ahead and make my request, but I'm not exactly sure how to do it in Objective-C.
I am using TouchJSON, however I'm not quite sure how to construct the correct JSON payload above and POST this to the server (also I'd prefer this to be an asynchronous request rather than a synchronous).
NSError *theError = NULL;
NSArray *keys = [NSArray arrayWithObjects:#"aps", #"badge", #"alert", #"aliases", nil];
NSArray *objects = [NSArray arrayWithObjects:?, ?, ?, ?, nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSURL *theURL = [NSURL URLWithString:#"https://go.urbanairship.com/api/push/"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSData *theBodyData = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary error:&theError];
[theRequest setHTTPBody:theBodyData];
NSURLResponse *theResponse = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseData error:&theError];
NSURL *url = [NSURL URLWithString:#"https://go.urbanairship.com/api/push/"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
//... set everything else
NSData *res = [NSURLConnection sendSynchronousRequest:req returningResponse:NULL error:NULL];
or send asynchronous request with
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:some];
have a look at NSMutableURLRequest Class Reference to see how to set what.
You can use NSURLConnection for this; here's a sample:
How do I make HTTP post request for getting JSON object in response for iPhone application?
There may be a way to actually run a curl script proper, using NSTask: http://borkware.com/quickies/one?topic=nstask
I searched a lot to convert this cUrl request to send Urban Airship push notifications, I finally did it below is the source code which worked for me:
Required:
ASIHTTPRequest //Required to execute Http request
+(void)sendUrbanAirshipPushWithPayload:(NSString *) payload
{
//payload = #"{"aps": {"badge": 1, "alert": "The quick brown fox jumps over the lazy dog."}, "aliases": ["12345"]}";
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:#"https://go.urbanairship.com/api/push/"]];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request setRequestMethod:#"POST"];
//Set the HTTP Basic Authentication header with the application key as the username, and the master secret for the password
[request setUsername:kUrbanAirshipKey];
[request setPassword:kUrbanAirshipMasterSecret];
[request setPostBody:[NSMutableData dataWithData:[payload dataUsingEncoding:NSUTF8StringEncoding]]];
[request startSynchronous];
if([request error])
{
NSLog(#"Code : %d, Error: %#",[[request error] code],[[request error] description]);
}
NSLog(#"Code: %d, Description: %#, Message: %#",[request responseStatusCode],[request responseData],[request responseStatusMessage]);
}
Related
So, I have to methods to approach a web service:
A GET:
- (NSDictionary *)getDataFromURL:(NSString*)url {
NSString * serverAddress =[NSString stringWithFormat:url,mySchoolURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL
URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: #"GET"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection
sendSynchronousRequest:request
returningResponse:&urlResponse
error:&requestError];
NSError* error = nil;
NSDictionary *output = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:nil];
return output;
}
and a POST:
-(NSData*)postData:(NSDictionary*)requestData toUrl:(NSString*)destination {
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:requestData options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:destination,mySchoolURL]]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postdata];
[request setHTTPMethod:#"POST"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
return nil;
}
Somehow, the HTTP header of the POST method does include the cookie's SessionID, while the GET one doesn't.
I have to admit that I don't fully understand the innards of cookies and the like, but several sources on the web claim that I should't worry about the cookies at all, since they are taken care of automatically.
Anyway, the web service I'm talking to expects a Session ID in both POST and GET situations, so now I'm forced to start understanding what's going on.
Could any of you help me out here?
The concrete question is: how to I pass a Session_ID to a URL using a GET method?
Thanks ahead
Okay so one way to do this is by simply adding the cookies to the HTTP headers. When doing this the correctness of the URL is key. If the protocol is wrong, some cookies may not be included. You will need to get all available cookies, and then create a dictionary for the headers with he available cookies. Then you simply add those headers to your request by calling setAllHTTPHeaderFields:. I placed a quick example of how to do this below, however you can learn more about how cookies work at the Apple Documentation Class Reference
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[request setAllHTTPHeaderFields:headers];
I really hope this helps you out. I would recommend reading the Apples Documentation to help you out as much as possible. I wish you the best of luck!
Good day,
I am trying to use a Codeigniter based API to connect with iOS and using NSURLRequest.
The API is in debugMode and for now it returns the same key value pair as json as the one that you are posting. I have tried posting the values to the link through postman and it works correctly, however when I post it through my iOS application, the json response is received but the array that should contain the post values is empty.
Here is the iOS Code snippet :
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSString * params = #"authkey=waris";
NSData * postData = [params dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
This is the response when I post the same parameters through postman ( A RESTFUL Client for Chrome )
{
"status": "1",
"data": {
"authkey": "warisali"
}
}
However when I query the same API from the above iOS Code I am getting this :
{
data = 0;
status = 1;
}
Any help on the matter will be highly appreciated!
I had same issue (not with CodeIgniter but with Ruby ...)
Try something like this, solved my problem.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSDictionary *paramDict = #{#"authkey": #"waris"};
NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:paramDict options:NSJSONWritingPrettyPrinted error:&error];
if (error)
{
NSLog(#"error while creating data %#", error);
return;
}
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
I ended up using the ASIHttpRequest + SBJson combo and that worked like Charm!
After adding the ASIHttpRequest core classes and SBJson Classes to parse the JSON, I was able to achieve what I wanted !
The problem is that because of the way you're creating the connection, it will start immediately, before you've finished configuring the request. Thus, you're creating a mutable request, creating and starting the connection, then attempting to modify the request and then trying to start the request a second time.
You can fix that by changing the line that says:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
To say:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
Or, easier, just move the original instantiation of the NSURLConnection (without the startImmediately:NO) after you've finished configuring your request, and then eliminate the [connection start] line altogether.
I came to the last stage of development of my app and here is the bit that I've never done before.
My friend has developed and API for my app to send and receive data, using django rest framework.
I need to authenticate my app to connect to it, send some data and receive data.
What I have found so far is:
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/my/path/to/api/login/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"myUsername", #"myPassword"];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", authData];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
//------------------------------------------------------------------------------------------------------------------------------------//
//EDIT: Added this based on answer form #Quver.
NSURLResponse *response1;
NSError *responseError;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response1 error:&responseError];
if (result.length > 0 && responseError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:result
options:0
error:NULL];
NSLog(#"Got response form server: %#", greeting);
}
This equals output like:
<0a0a3c68 746d6c3e 0a0a2020 20203c68 6561643e 0a202020 20202020 200a2020 20202020 20200a20 20202020 + ~50 lines of similar stuff. Hope this helps.
//-----------------------------------------------------------------------------------------------------------------------------------------//
I guess this is the way to create request. What should I do next? And how do I know that I have connected?
Then, if I have connected, how do I get data form there? (I have a url that gives me json as output - this is what I want to get). Assume the url to be http://localhost:8080/url/that/gives/json/.
Thank you for any help. Hope this is enough information for the question. I will add anything else required.
NSURLResponse *response;
NSError *responseError;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&responseError];
Add this to get response. You already prepared request, now it's time to send it with NSURLConnection. I you sync request insted of async, becouse of using GCD for whole metod request + sqlite update.
After a few days of searching I have found a way.
First, we need a token for authentication. I am generating it through terminal for now:
curl -X POST -d "grant_type=password&username=<your username>&password=<your password>" http://<client secret>:<client id>#url/to/token/page
Then, in your view controller where you want to connect:
//always put </> at the end of link
NSURL *aUrl = [NSURL URLWithString: #"http://where/you/trying/to/conect"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request addValue:[NSString stringWithFormat:#"<type> <your token>"] forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
NSError *error = nil;
self.response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error: &error];
This will return any json that the page supposed to return. This might not be the most secure way, but this is exactly what I need for now. I will look at more secure solutions like OAuth 2, later.
Hope this helps to someone.
Hi I am sending an http post request to a server the java code i am referring to has a method as set entity in the post request. How can i achieve this in iOS .
I am presently putting the json data to be sent in the body but am getting the error
Error 500 Cannot read request parameters due Invalid parameter, expected to be a pair
but was
{
"chatMessage" : {
"reportRequest" : "Sent",
"text" : "wdfsds acd"
}
my code is
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[var.projectUsername base64EncodedString] forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPShouldHandleCookies:YES];
NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:messageText.text,#"text",#"Sent",#"reportRequest",nil];
NSDictionary *dictionary1 = [NSDictionary dictionaryWithObjectsAndKeys:dictionary,#"chatMessage", nil];
NSError *error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary1 options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPBody:jsonData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Add this in your code:- [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
I think the title explains it. I can reach the Get functions on my api controllers just fine. I can reach the Post method, but my parameter (macAddress) is null. I've tried many variations of this code in xcode:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",baseURL,controller]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"macAddress=testestest";
NSData *myRequestData = [ NSData dataWithBytes: [ postString UTF8String ] length: [ postString length ] ];
[request setHTTPBody:myRequestData];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
and the controller:
public String Post([FromBody]string macAddress)
{
//......
}
(I'm aware that I'm using synchronous requests and nil response/errors, just trying to figure out this aspect)
Thanks for the help.
It looks like you have your *postString without the [NSString stringWithFormat method]. I use the following code with my own restful API.
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"rsdevicetoken"];
NSString *postString = [NSString stringWithFormat:#"token=%#&active=%#&draw=%#&result=%#&message=%#",deviceToken,allNotify, draw, results, message];
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.someurl.com/updateSubscriptions"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#", data);
Hopefully this will help you.
It's a wild guess but if your macAddress post param has the following format: 01:23:45:67:89:ab you need to url encode the ':' to '%3A'.