NSMutableURLRequest returns old values even cachePolicy is NSURLCacheStorageNotAllowed - objective-c

Im using codes posted here:
connection release method in connectionDidFinishLoading, causes error
now first execute returns didFail log.
second execute; returns old response data.
albeit my (localhost) server is totally offline.
and cachePolicy is NSURLCacheStorageNotAllowed (check the code on the link I posted above)
NSMutableURLRequest *request=
[NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:3.0f];
the response data seems cached somewhere and still exists.
but if I use NSURLRequestReloadIgnoringLocalAndRemoteCacheData //which is commented as -not implemented-
not returns old cache.
but if so what is the difference between:
NSURLRequestReloadIgnoringLocalAndRemoteCacheData
and
NSURLCacheStorageNotAllowed
what shall I do ?

NSURLCacheStorageNotAllowed refers to NSCachedURLResponse and is an value of enum NSURLCacheStoragePolicy. Since the cache policy of NSMutableURLRequest is also an enum (NSURLRequestCachePolicy) you just pass wrong int to the static method creating NSMutableURLRequest. In this case NSURLCacheStorageNotAllowed is just 2 which equals to NSURLRequestReturnCacheDataElseLoad - and that is why you get old data.

Try This
NSString *Post = [[NSString alloc] initWithFormat:#"Post Parameters"];
NSURL *Url = [NSURL URLWithString:#"Url"];
NSData *PostData = [Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [PostData length]];
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:Url];
[Request setHTTPMethod:#"POST"];
[Request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[Request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[Request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[Request setHTTPBody:PostData];
NSError *error;
NSURLResponse *response;
NSData *Result = [NSURLConnection sendSynchronousRequest:Request returningResponse:&response error:&error];
if (!Result)
{
NSLog(#"Error");
}
else
{
//Parse the result
}

Related

Objective C NSMutableURLRequest GET request returns null JSON

trying get Data from server using #"GET" request,
this following code returns null all time:
is anybody finding an issue with my following code?
or it's can be server side Issue..
?
thank for your help!
+ (id)sendParam:(NSString*)ParamString url:(NSString*)url{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
NSString *post = ParamString;
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setURL:[NSURL URLWithString:url]];
NSLog(#"postLength =%#",postLength);
[request setHTTPBody:postData];
[request setHTTPMethod:#"GET"];
[request addValue:ParamString forHTTPHeaderField:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSMutableArray*jsonReturn = [[NSMutableArray alloc]init];
jsonReturn = (NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
NSLog(#"jsonReturn %#",jsonReturn);
return jsonReturn;
}
after Editing:
+ (id)sendParam:(NSString*)ParamString url:(NSString*)url{
NSString*StringGETMETHOD = [NSString stringWithFormat:#"%#%#",url,ParamString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:StringGETMETHOD]];
[request setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"aData=%#",aData);
if (aData) {
jsonReturn=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
NSLog(#"jsonReturn %#",jsonReturn);
}
If you want to use GET for getting response from server just you can try in following method
//just give your URL instead of my URL
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[[jsonArray objectForKey:#"search_api"]objectForKey:#"result"];
I very much doubt that you should send this parameter as a HEADER field.
I also would think that you should be sending a POST and not a GET.
Setting jsonReturn to [[NSMutableArray alloc] init] is nonsense. Explain to yourself why you are doing it instead of setting jsonReturn to nil
Logging the jsonReturn is nonsense, because all the interesting stuff has disappeared. You should log the response and the data that was returned, at least if jsonReturn = nil.
You seem to be confused between GET and POST. You are doing a GET, but supplying data like a POST (usually does, though it isn't mandated, or precluded to use the body data for a GET).
Generally, you don't want to use body data for a GET, it isn't usual / expected so any number of different issues could be occurring. Either change setHTTPMethod: to #"POST" so you are doing a POST properly, or change the parameters to be part of the request URL.
It really all depends what the server expects (and can handle). This is what you need to know and match against...
Subsequently you have a different issue. The param string you supply has characters in it that need to be encoded (like spaces). Use stringByAddingPercentEscapesUsingEncoding: on the param string before you send it to escape these characters.
It works in a browser because it is adding the escape characters for you (which you should see in the browser address bar after it has loaded the response).
i found my issue:
sending paramString Using "Get" Method, cannot send parameters with space between letters.. example: "tel aviv" should be "tel%20aviv"
by adding the following code line:
**urlParam = [urlParam
stringByReplacingOccurrencesOfString:#" " withString:#"%20"];**
fix code:
+ (id)sendParam:(NSString*)ParamString url:(NSString*)url{
NSString* urlParam = [NSString stringWithFormat:#"%#%#",url,ParamString];
urlParam = [urlParam
stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlParam]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"aData=%#",aData);
if (aData) {
jsonReturn=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
NSLog(#"jsonReturn %#",jsonReturn);
}
thank you all !

iOS http post response to NSDictionary or NSArray

I'm making a HTTP Post and I would like to know how to convert the response to NSDictionary, or NSArray. Here's my code:
NSString *post = [NSString stringWithFormat: #"SomeData=text", text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https://www.my.site/receiver"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
EDIT:
The response looks like this after converting like this:
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
2011-12-04 11:50:00.924 Dancing Ruby[404:207] response: SID=DQAAAMAAAAAjy9MXrxh7Hi4nXTpyVTnqMR4c_W2wCQmLmO7xDHz7v91kl16tH-0UyazONU2nGjsUYxGzAPd9lvNcCGLfcz7YFLQRhG8yW8_wn3V46g8SY0A5bnfmGhuIbAMoCetow09cOnE7aYUzEZ4u5zVnJFoNepa9BlheFAA8JFLomw3luHedLkJZi_CQJO48CtwLZeIF9zhD5RNUDUretNh_1QBN2fHntSiqASMHHHyd9dtlTaXpokx_KIJovxo0dNYUJbs
LSID=DQAAAMIAAACgjuwUzSRNh2xXrWsdA81_fLVCguvatiHHU6b1dMm0TD6-lQyl-odfIfLGWgee4_j3HXUNsqtTm-aEFgylW2QURA5F9_1Fx8WRECIWOkUoLfWBGchoxRfhxKqCoD-zzgg1opjSmrDyv0U1NZRN7YGiqkLj4Fz_Qm6oPapov2_J33KT0ENFTKnqyzS0zU3wHgKSGb1aoKKO0ZJCTFk20AX3cLYPuMWoJcnyrLipCzZjkjwGEEhfgz31ISPS9OGezPzYJji-UxTmaJB7Va7SGquX
Auth=DQAAAMEAAACgjuwUzSRNh2xXrWsdA81_fLVCguvatiHHU6b1dMm0TD6-lQyl-odfIfLGWgee4_gex6ZHpCOn0tXFwuivD7ESwhFMJGdLRYSspk-leGqj-eCkXUgsg4DBvxPbdpREFlU_j0RGm_qufXlaScZV3x17plY5-xrhvhziEVFf3eLiHEmN9HHNwh8uElyYyJ1rLNAbIunpG3D10ASr4WPQDIz_52OOKy07CmQrBNDdUcpkT5bXqBe3Cdw8aqld0LZH2AIMEdj7PupfRaneJgF-nCBZ
You need to use some kind of parser for that. If the response is in XML you could use NSXMLParser. Here you can find a tutorial on how to use it. The same concept applies for any other kind of data. You have to know beforehand what to expect so you can parse it properly.
I hope it helps

POST to server results in GET request

I'm trying to do a simple POST request to a server, with this code:
NSString *post = [[NSString alloc] initWithFormat:#"email=%#&password=%#", self.email.text, ..]; // .. simplified keychainItem
NSData *postEncoded = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postEncoded length]];
NSURL *url = [NSURL URLWithString:#"http://eng.studev.groept.be/web2.0/a11_web02/testApp.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postEncoded];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
When debugging on the server, this actually results in a GET request. That explains why I'm getting a PHP error when trying to read $_POST[ ] variables. Bottom line: why isn't the setHTTPMethod: being accepted?
(extra information: when just coding in PHP on the server, use of POST works normally)

Implement Timeout in HTTP Post

What is the best way to implement a connection timeout (let's say, 20 seconds) within an HTTP post connection?
My current code is as follows:
-(NSData*) postData: (NSString*) strData
{
//postString is the STRING TO BE POSTED
NSString *postString;
//this is the string to send
postString = #"data=";
postString = [postString stringByAppendingString:strData];
NSURL *url = [NSURL URLWithString:#"MYSERVERHERE"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [postString length]];
//setting prarameters of the POST connection
[request setHTTPMethod:#"POST"];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[request addValue:#"en-US" forHTTPHeaderField:#"Content-Language"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setTimeoutInterval:10.0];
NSLog(#"%#",postString);
NSURLResponse *response;
NSError *error;
NSLog(#"Starting the send!");
//this sends the information away. everybody wave!
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Just finished receiving!");
if (&error) //OR TIMEOUT
{
NSLog(#"ERROR!");
NSString *errorString = [NSString stringWithFormat:#"ERROR"];
urlData = [errorString dataUsingEncoding:NSUTF8StringEncoding];
}
return urlData;
}
Obviously the timeout interval is set to 10.0, but nothing seems to happen when those ten seconds hit.
See:
NSMutableURLRequest timeout interval not taken into consideration for POST requests
Apparently timeouts under 240 seconds are ignored. The highest voted answer in that question links to a solution. However, I would simply recommend using the ASIHTTPRequest library instead.
http://allseeing-i.com/ASIHTTPRequest/

Put JSON encoded array as NSData from NSURLResponse into NSArray

I'm unable to get this to work:
NSString *post = [NSString stringWithFormat:#"userudid=%#", [udid stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",post);
NSData *postData = [NSData dataWithBytes:[post UTF8String] length:[post length]];
//[udid dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSLog(#"%#",postData);
//NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.myserver.com/myapp/readtags2.php"]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
//[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *content = [NSString stringWithUTF8String:[urlData bytes]];
NSLog(#"responseData: %#", content);
is the POST formed correctly? Because i can get it to work from a manual html form posting to the same php file, but i get nothing back when doing it from iOS
You might have an easier time doing HTTP POST's with ASIHTTPRequest.
Form-Posting with ASIHTTPRequest is explained in the section titled "Sending a form POST with ASIFormDataRequest" here: http://allseeing-i.com/ASIHTTPRequest/How-to-use
Otherwise, have a look at the NSURLResponse, check the response code and see if iOS thinks the POST was successful.
Other thing you can use to check is a tool like wireshark to compare the network traffic from your web-based form POST to the traffic from your iOS POST. It looks like you're doing it right, but the best way to be sure is something like wireshark.