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.
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!
I have this json:
{"myFriends":{"userId":"the user id", "userName":"the user name", "friends":[{"u":"friend user id","n":"friend user name"},{"u":"friend user id","n":"friend user name"}]}}
and I want to send him in post request to the server, this is the current way I am trying to do this:
+(NSData *)postDataToUrl:(NSString*)urlString :(NSString*)jsonString
{
NSData* responseData = nil;
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSString *bodydata=[NSString stringWithFormat:#"%#",jsonString];
[request setHTTPMethod:#"POST"];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPBody:req];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"the final output is:%#",responseString);
return responseData;
}
The json string contains the json, but for some reason the server always get nil and return error. How to fix this?
It would certainly help to tell your server about the content type:
[request addValue:#"application/json"
forHTTPHeaderField:#"Content-Type"];
Furthermore: in my own code I use:
[request setHTTPBody:[bodydata dataUsingEncoding:NSUTF8StringEncoding]]
This is my code for POST request with an NSData parameter:
- (void)uploadJSONData:(NSData*)jsonData toPath:(NSString*)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimeout];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: data];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[data length]] forHTTPHeaderField:#"Content-Length"];
// Create url connection and fire request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
}
This is for an asynchronous request, but it should work just fine for synchronous. The only thing I see you might be missing is the "Content-Length" parameter.
I'm building an iOS app and posting a data to api. I'm facing a problem that i posted a once
but it is reflected twice on the server.And i have checked from rest clients that there is no error at the server side.
here is my code
- (void) next: (UIButton*) sender
{
NSString *post =[NSString stringWithFormat:#"? &sportsname=%#&time=%#&venue=%#&date=%#&players=%#&addinfo=%#&userid=%#&gender=%#&recurring=%#",_selectedSport,_selectedTime,location,dateValue,max,info,UserId,_selectedGender,_selectedRecurring];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://yy.4.yyy.hh:iyiy/api/user/%#/host",UserId]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[self performSegueWithIdentifier:#"hostSubmit" sender:nil];
if(conn)
{
NSLog(#"Connection successfull");
}
else
{
NSLog(#"connection could not be made");
}
}
It's pretty easy to link the same action twice in a button. Look at the actions tab in interface builder and make sure you haven't linked your button to your next: action twice.
Failing that, add a log statement at the beginning of the method "entering method 'next:'" and see if you see the log twice. If you do, go figure out why.
I am currently building an app in Xcode using Objective C and I need to post two text variables and an image. As of right now, I can only post the two text variables but I would like to send an image from my UIImageView to the server by using the FILES variable from the HTTP POST Request.
Here is the working code for my POST Request:
- (IBAction)posttoserver:(id)sender {
NSString *post = [NSString stringWithFormat:#"process=writepost&auth_token=%#&app_id=0&posttextarea=%#&url=%#", authkey, encodedmessage, encodedlink];
NSData *data = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postlength = [NSString stringWithFormat:#"%lu", (unsigned long)[data length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"my-server.com"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
NSLog(#"Connection!");
}
else {
NSLog(#"No Connection");
}
[_posttext resignFirstResponder];
[_postlink resignFirstResponder];
}
Continued:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Post Response: %#", response);
if ([response isEqualToString:#"success"]) {
// NSLog Success
}
else {
// Something is wrong
}
}
As you can see, I am posting the user editable text as well as a link for the post. Also, you might notice that I am attaching "process=writepost&auth_token=%#&app_id=0" and those are just needed for the server to recognize who is posting and what process is being sent to the specific URL.
Now, I would like to attach an image to the POST request by adding an image from the UIImageView. How would I attach it into the FILES variable for the POST request?
Any help would be gladly appreciated.
Thanks in advance,
Kyle
// Web service request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
//returndata is response of webservice
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue] ;
NSLog(#"chat data- %#",results);
NSString *strResults = [results objectForKey:#"d"];
NSLog(#"result string is-%#",strResults);
this is the code that I am using for my Data fetching from web service. But i have to do this every time when come to this page.
Is that any method that can store my data in Cache memory so i need not to request every time.
I Am using
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
but i dont know how to use - (NSCachedURLResponse *) connection this method
thanks...
You need to use cache as of your needs according to this documentation: whenever you requesting a NSMutableURLRequest...
For Ex:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];
For More details Kindly look into the Documentation