I want to send a string like #"projects 02.03.2012" to the backend and receive back a json response with list of projects selected according to the string I send. The back end will be done for me, but I wonder how the request url should look like and whether I will receive proper response. Here is what I've got so far, the request url is just for test.
-(void)requestProjects
{
responseData=[[NSMutableData alloc] init];
responseArray=[[NSMutableArray alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://search.twitter.com/search.json?q=mobtuts&rpp=5"]];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failed!");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue];
NSLog(#"Response: %#", results);
}
Related
I'm trying to connect my application to the backend using NSURLConnection.
When I use postman everything works really fine and I get the expected result.
But when I try that in my code I get a totally different result, which is a JSON object from the server but with an error message.
Please check the following pictures and the code I use for more details.
Any idea will be really appreciated .
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlStr=[NSString stringWithFormat:#"URL"];
NSURL* _url=[NSURL URLWithString:urlStr];
[request setURL:_url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"Bearer ---" forHTTPHeaderField:#"Authorization"];
NSArray *keys= [[NSArray alloc] initWithObjects:#"email",#"firebase_token",#"password",#"username",#"phone",#"uploaded_file", nil];
NSArray *values = [[NSArray alloc] initWithObjects:email,#"token",password,userName,phone,#"#/C:/Users/admin/Downloads/chili house.png", nil];
NSDictionary *params = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted
error:&error];
[request setHTTPBody:jsonData];
NSString *jsonString;
if ( jsonData) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setHTTPBody:jsonData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
if ([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:#"User"
password:#"Password"
persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential
forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection failed: %#", [error description]);
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.responseData setLength:0];
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[[BusyAgent defaultAgent] makeBusy:NO];
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
if (responseString == (id)[NSNull null] || responseString.length == 0 ){
NSLog(#"responseString= %#",responseString);
}else{
NSLog(#"responseString = %#",responseString);
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:responseString delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok", nil];
[alert show];
}
self.responseData = nil;
}
I am using a GET for getting a data from Server, Want to implement a progressbar, for that i tried to capture expectedContentLength in the didReceiveResponse delegate method.
How can it can be solved?
NSString* serverUrl = #"https:testURL";
receivedData = [[NSMutableData alloc] initWithLength:0];
NSURL* url =[NSURL URLWithString:[serverUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setValue:#"identity" forHTTPHeaderField:#"Accept-Encoding"];**(I tried it after seeing other solutions over Web)**
[NSURLConnection connectionWithRequest:theRequest delegate:self];
...
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData setLength:0];
expectedBytes = [response expectedContentLength];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
_contentLength = [response expectedContentLength];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
_receiveLength += data.length;
}
Do you think so?
In ViewDidLoad method I have added the below code
self.responseData = [NSMutableData data];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:#"my url"]];
[request setHTTPShouldHandleCookies:YES];
[request setHTTPMethod:#"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
And When connection start delegate methods are calling
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSUInteger responseStatusCode = [httpResponse statusCode];
_responseData = [[NSMutableData alloc] init];
NSLog(#"connection");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
NSLog(#"_responseData%#",_responseData);
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *jError;
jArray= [NSJSONSerialization JSONObjectWithData:_responseData options:NSJSONReadingMutableContainers error:&jError];
[_tableView reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"didFailWithError");
}
This is the way am hitting HTTPS URL but it was taking more time to display the data.Am not getting what is the issue.Can anyone please help me on this issue.
I know about how to post data (UITextField values) to JSON url using POST.But now i tried post Data using GET method to server.I have 10 textFields.I tried like this way
NSString *post1 =[NSString stringWithFormat:#"?&dealImage=%#&dealcatid=%#&DeaTitle=%#&DealDesc=%#&price=%#&cityId=%#&StartDate=%#&EndDate=%#&FromTime=%#&ToTime=%#",
strEncoded, string1 ,pTitle.text ,Description.text ,pPrice.text,string2,beginDate,endDate,beginTime,endTime];
NSData *postData = [post1 dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSLog(#"array array %#",postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.3.125:8090/SaveDollar/rest/deals/add"]]];
NSLog(#"getData%#",request);
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSLog(#"getData%#",request);
con3 = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(con3)
{
webData3=[NSMutableData data];
NSLog(#"Connection successfull");
NSLog(#"GOOD Day My data %#",webData3);
}
else
{
NSLog(#"connection could not be made");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (connection ==con3)
{
[webData3 setLength:0];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (connection ==con3)
{
[webData3 appendData:data];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if (connection ==con3) {
NSLog(#"SOMETHING WENT WRONG WITH URL3");
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (connection==con3)
{ NSLog(#"Succeeded! Received %d bytes of data",[webData3 length]);
NSLog(#"Data is %#",webData3);
NSString *responseText = [[NSString alloc] initWithData:webData3 encoding: NSASCIIStringEncoding];
NSLog(#"Response: %#", responseText);//holds textfield entered value
NSString *newLineStr = #"\n";
responseText = [responseText stringByReplacingOccurrencesOfString:#"<br />" withString:newLineStr];
NSLog(#"ResponesText %#",responseText);
}
}
When after submit console will be show this message"SOMETHING WENT WRONG WITH URL3"
I know posting but now I need post Data and the Get Response also.So I used GET Method but i am not getting response.So Please give me any idea. And then Please tell me what wrong in my code.
Use the callback function
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
If the call is failing the error variable will help you see what is going wrong so you can figure it out yourself.
One thing which might help too is to set your request's content-type field to application/json.
you should collect response data like this:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// connection fail
}
where data is NSMutableData *_responseData;
I'm making an NSURLConnection to my server but responseData ends up being null in connectionDidFinishLoading and I can't figure out why. Here's the code for the connection:
NSMutableData *responseData;
- (void)myFunction:(id)sender {
NSString *url = #"http://www.example.com/";
NSURL *URL = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
// NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
} // end connectionDidFinishLoading
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection error: %#",[error description]);
}
responseData isn't initialized :)
Typical! Just as I finished posting the question the answer dawned on me. I never initialized responseData. So in viewDidLoad I added the line below:
- (void)viewDidLoad
{
[super viewDidLoad];
responseData = [NSMutableData data];
}