NSURLConnection connection: didReceiveData: is not called after redirect - objective-c

I am starting a request which gives me back HTML with a redirection inside. Why is the didReceiveData function not called a second time? I am trying to download a JSON File. (Using iOS6)
- (void) testdownload{
NSURL *url = [NSURL URLWithString:#"https://***];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d{
NSString *tmpdata = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
NSLog(#"data: %#", tmpdata);
}
When i use a UIWebView the redirection will be handled and the JSON file will be shown. Playing with this function didn't work:
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse{
return request;
}

Try using this code instead:
- (NSURLRequest *)connection: (NSURLConnection *)inConnection
willSendRequest: (NSURLRequest *)inRequest
redirectResponse: (NSURLResponse *)inRedirectResponse;
{
if (inRedirectResponse) {
NSMutableURLRequest *r = [[request mutableCopy] autorelease]; // original request
[r setURL: [inRequest URL]];
return r;
} else {
return inRequest;
}
}
Learn more on this SO question

I used this now instead (but not realy nice):
- (IBAction)redirectTest:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://billstclair.com/html-redirect.html"];
_request = [NSURLRequest requestWithURL:url];
UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectNull];
webview.delegate = self;
[webview loadRequest:_request];
[self.view addSubview:webview];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *content = [webView stringByEvaluatingJavaScriptFromString:#"document.getElementsByTagName('html')[0].innerHTML"];
NSLog(#"content: %#",content);
}

Related

how can I use NSURLConnection Asynchronously?

I am using this code to load data to my App, can you tell me how can I make this asynchronously?
NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
if (connection)
{
NSLog(#"NSURLConnection connection==true");
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&response error:&err];
self.news =[NSJSONSerialization JSONObjectWithData:responseData options:nil error:nil];
NSLog(#"responseData: %#", self.news);
}
else
{
NSLog(#"NSURLConnection connection==false");
};
I think you should be bothered reading the documentation. There's a sendAsynchronousRequest:queue:completionHandler: method.
Create the connection with initWithRequest:delegate:startImmediately:, set yourself as its delegate and implement the delegate methods.
Block code is your friend. I have created a class which does this for you
Objective-C Block code. Create this class here
Interface class
#import <Foundation/Foundation.h>
#import "WebCall.h"
#interface WebCall : NSObject
{
void(^webCallDidFinish)(NSString *response);
}
#property (nonatomic, retain) NSMutableData *responseData;
-(void)setWebCallDidFinish:(void (^)(NSString *))wcdf;
-(void)webServiceCall :(NSString *)sURL_p : (NSMutableArray *)valueList_p : (NSMutableArray *)keyList_p;
#end
Implementation class
#import "WebCall.h"
#import "AppDelegate.h"
#implementation WebCall
#synthesize responseData;
-(void)setWebCallDidFinish:(void (^)(NSString *))wcdf
{
webCallDidFinish = [wcdf copy];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int responseStatusCode = [httpResponse statusCode];
NSLog(#"Response Code = %i", responseStatusCode);
if(responseStatusCode < 200 || responseStatusCode > 300)
{
webCallDidFinish(#"failure");
}
[responseData setLength:0];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"WebCall Error: %#", error);
webCallDidFinish(#"failure");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
response = [response stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
webCallDidFinish(response);
}
-(void)webServiceCall :(NSString *)sURL_p : (NSMutableArray *)valueList_p : (NSMutableArray *)keyList_p
{
NSMutableString *sPost = [[NSMutableString alloc] init];
//If any variables need passed in - append them to the POST
//E.g. if keyList object is username and valueList object is adam will append like
//http://test.jsp?username=adam
if([valueList_p count] > 0)
{
for(int i = 0; i < [valueList_p count]; i++)
{
if(i == 0)
{
[sPost appendFormat:#"%#=%#", [valueList_p objectAtIndex:i],[keyList_p objectAtIndex:i]];
}
else
{
[sPost appendFormat:#"&%#=%#", [valueList_p objectAtIndex:i], [keyList_p objectAtIndex:i]];
}
}
}
NSData * postData = [sPost dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSURL * url = [NSURL URLWithString:sURL_p];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
if (theConnection)
{
self.responseData = [NSMutableData data];
}
}
#end
Then you to make this web call, you call it like this
WebCall *webCall = [[WebCall alloc] init];
[webCall setWebCallDidFinish:^(NSString *response){
//This method is called as as soon as the web call is finished
NSString *trimmedString = [response stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([trimmedString rangeOfString:#"failure"].location == NSNotFound)
{
//Successful web call
}
else
{
//If the webcall failed due to an error
}
}];
//Make web call here
[webCall webServiceCall:#"http://www.bbc.co.uk/" :nil :nil];
See the setWebCallDidFinish method, it will not be called until the webcall has finished.
Hope that helps!!
Here is some code which I am using in my app:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:yourURL]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Error loading data from %#. Error Userinfo: %#",yourURL, [error userInfo]);
} else {
NSDictionary *dataFromServer = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
contentAsString = [[[dataFromServer objectForKey:#"page"] objectForKey:#"content"] stripHtml];
completionHandler(contentAsString);
}];
fyi: stripHTML is a NSString Category to remove HTML tags from JSON --> Found it Here
you can call your content in your class like that:
[yourClass getDataWithcompletionHandler:^(NSString *content) {
yourObject.content = content;
[yourClass saveManagedObjectContext];
}];
if you implement it once, you won't want to use synchronous connection again...
Check this out: HTTPCachedController
It will help you send POST and GET requests, while it will cache the response and after that it will return the cached data when no internet connection is available.
HTTPCachedController *ctrl = [[[HTTPCachedController alloc] initWithRequestType:1 andDelegate:self] autorelease];
[ctrl getRequestToURL:#"https://api.github.com/orgs/twitter/repos?page=1&per_page=10"];
You will get notified when the data are fetched through a delegate method:
-(void)connectionFinishedWithData:(NSString*)data andRequestType:(int)reqType

Objective C NSURLConnection dosen't get response data

I am creating this application, it communicates with a PHP script on my web-server.
Last night it was working perfectly. But today two of the connections does not get response.
I've tried the NSURL link in my browser, it works fine. Also one of the connections work, but as i said two connections does not work?
- (void) getVitsTitelByID:(int)id {
NSString *url = [NSString stringWithFormat:#"http://webserver.com /ivitserdk.php?function=gettitelbyid&id=%d", id];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1.0];
connectionTitelByID = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
connectionDidReciveData:
if(connection == connectionTitelByID){
responseTitel = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
connectionDidFinishLoading:
if(connection == connectionTitelByID){
titelLabel.text = responseTitel;
}
I've tried and debugging it.
responseTitel seems to be (null).
Help would be apriceated :)
didReceiveData may be called N (several) times. save the data to a mutably data buffer (queue it up) and in didFinish read it into a string
mock code:
- (void) getVitsTitelByID:(int)identifier {
NSString *url = [NSString stringWithFormat:#"http://webserver.com/ivitserdk.php?function=gettitelbyid&id=%d", identifier];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1.0];
connectionTitelByID = [[NSURLConnection alloc] initWithRequest:request delegate:self];
dataForConnectionTitelByID = [NSMutableData data];
[connectionTitelByID start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if(!data.length) return;
if(connection == connectionTitelByID)
[dataForConnectionTitelByID appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if(connection == connectionTitelByID) {
id str = [[NSString alloc] initWithData:dataForConnectionTitelByID encoding:NSUTF8StringEncoding];
NSLog(#"%#",str);
dataForConnectionTitelByID = nil;
connectionTitelByID = nil;
}
}

NSURLConnection GET and POST not working

I am not getting the correct output from the server. The response I get back everytime is:
Gone
/prod/bwckgens.p_proc_term_datehas been permanently removed from this server.
This is usually recieved when you just direct the web browser to the page here instead of going through this page first. This makes me come to the conclusion that a cookie isn't being saved, but I read in the documentation that this is all handled by the NSURLConnection object. Is there something I am doing wrong here?
#import "PCFViewController.h"
#interface PCFViewController ()
#end
NSMutableData *mutData;
#implementation PCFViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)queryServer {
NSURL *url = [NSURL URLWithString:#"https://selfservice.mypurdue.purdue.edu/prod/bwckschd.p_disp_dyn_sched"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:3.0];
//the reason I perform a GET here is just to get a cookie and communicate like a normal web browser, since directly doing a POST to the proper address isn't working
[request setHTTPMethod:#"GET"];
[request setValue:#"text/html; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
mutData = [NSMutableData data];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[mutData length]);
NSString *str = [[NSString alloc] initWithData:mutData encoding:NSUTF8StringEncoding];
//just to see the contents(for debugging)
NSLog(#"%#", str);
[self handleConnection:connection];
}
-(void)handleConnection:(NSURLConnection *)connection
{
//this is the first step
if ([#"/prod/bwckschd.p_disp_dyn_sched" isEqualToString:[[[connection originalRequest] URL] path]]) {
//first request
//POST
NSURL *url = [NSURL URLWithString:#"https://selfservice.mypurdue.purdue.edu/prod/bwckgens.p_proc_term_date"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:3.0];
[request setHTTPMethod:#"POST"];
NSString *args = #"p_calling_proc=bwckschd.p_disp_dyn_sched&p_term=201320";
NSData *requestBody = [args dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestBody];
connection = [connection initWithRequest:request delegate:self];
[connection start];
if (connection) {
mutData = [NSMutableData data];
}
//second step. Here I send the list of classes(COMPUTER SCIENCE) I want to display as well as the term SPRING2013
}else if([#"/prod/bwckgens.p_proc_term_date" isEqualToString:[[[connection currentRequest] URL] path]]) {
NSURL *url = [NSURL URLWithString:#"https://selfservice.mypurdue.purdue.edu/prod/bwckschd.p_get_crse_unsec"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowed
timeoutInterval:3.0];
[request setHTTPMethod:#"POST"];
NSString *args = #"term_in=201320&sel_subj=dummy&sel_day=dummy&sel_schd=dummy&sel_insm=dummy&sel_camp=dummy&sel_levl=dummy&sel_sess=dummy&sel_instr=dummy&sel_ptrm=dummy&sel_attr=dummy&sel_subj=CS&sel_crse=dummy&sel_title=dummy&sel_schd=%25&sel_from_cred=&sel_to_cred=&sel_camp=%25&sel_ptrm=%25&sel_instr=%25&sel_sess=%25&sel_attr=%25&begin_hh=0&begin_mi=0&begin_ap=a&end_hh=0&end_mi=0&end_ap=a";
NSData *requestBody = [args dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestBody];
connection = [connection initWithRequest:request delegate:self];
[connection start];
if (connection) {
mutData = [NSMutableData data];
}
//the courses should be shown now I have to parse the data
}else if([#"/prod/bwckschd.p_get_crse_unsec" isEqualToString:[[[connection currentRequest] URL] path]]) {
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"%#\n", error.description);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[mutData setLength:0];
NSLog(#"%#\n", response.description);
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutData appendData:data];
}
#end
You cannot change the Request Object with the same URL Connection once it is started. Read the documentation of NSURLConnection. it says:
The URL request to load. The request object is deep-copied as part of
the initialization process. Changes made to request after this method
returns do not affect the request that is used for the loading
process.
So if you want to hit another URL, you have to create a new URLRequest and new URLConnection object. regarding your question about saving cookies. you can set the cache policy of the URLRequest using the following method
- (void)setCachePolicy:(NSURLRequestCachePolicy)policy

How to validate Username and password with Webserver values in I phone application

I am developing view based application.I have login page when we click on Login button it should check entered values with webserver values and it should display vali or invalid.I have wriiten code in this way it is executing successfully i am getting the result in this way
<!DOCTYPE html PUbLIC" -//W3C//DTD XHTML 1.0 Strict....
What i need to change in below code to comapre with server values..can any one help me regarding this please...
-(IBAction)buttonClick:(id)sender
{
NSString* username = nameInput.text;
NSString* pass = passInput.text;
if([nameInput.text isEqualToString:#"" ]|| [passInput.text isEqualToString:#""])
{
greeting.text = #"Input Your Value";
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
return;
}
NSString *post =
[[NSString alloc] initWithFormat:#"uname=%#&pwd=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"https://108.16.210.28/Account/LogOn"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
}
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
nameInput.text = nil;
passInput.text = nil;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(loginStatus);
greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
}
- (void)dealloc {
[super dealloc];
}
#end
Use statusCode to see the login state.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
if([response isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *theResponse = (NSHTTPURLResponse*)response;
NSInteger theStatusCode = [theResponse statusCode];
}
}
you have to parse the data.If it is in the form of XML data then you have to parse the element (like valid) in the didfoundcharacters.If it is valid then make a variable like BOOL confirm = NO;Modify this in the didfoundcharacters.if (confirm) then give access further

how to call under viewdid load data when button click event action is done

I am developing Viewbased application.I have method look like this.-(IBAction)switchPage:(id)sender this method is button click event action. Now when we click on button it should load under view did load data but it is not loading can any one help regarding this
-(IBAction)switchPage:(id)sender
{
if(self.viewTwoController == nil)
{
ViewTwoController *viewTwo = [[ViewTwoController alloc]
initWithNibName:#"View2" bundle:[NSBundle mainBundle]];
self.viewTwoController = viewTwo;
[viewTwo release];
}
[self.navigationController pushViewController:self.viewTwoController animated:YES];
[connection release];
}
//in viw did load i have this code
- (void)viewDidLoad {
[super viewDidLoad];
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://108.16.210.28/Account/LogOn"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (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 {
// label.text = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *post =[[NSString alloc] initWithFormat:#"usernameField=%#&passwordField=%#",usernameField.text,passwordField.text];
NSURL *url=[NSURL URLWithString:#"https://108.16.210.28/SSLLogin/Account/LogOn"];
NSLog(post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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];
/* when we user https, we need to allow any HTTPS cerificates, so add the one line code,to tell teh NSURLRequest to accept any https certificate, i'm not sure about the security aspects
*/
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
}
enter code here
As an optimization, NSViewControllers don't load their views until the last moment, i.e. when the view is actually accessed. So to load your view immediately just call [viewTwoController view] after its initialization and nib will be loaded, and your viewDidLoad method will be called.
Edit: Your code would look like this:
-(IBAction)switchPage:(id)sender {
if(self.viewTwoController == nil) {
ViewTwoController *viewTwo = [[ViewTwoController alloc]
initWithNibName:#"View2" bundle:[NSBundle mainBundle]];
self.viewTwoController = viewTwo;
[viewTwo release];
[viewTwo view] // calls loadView, loads the nib then calls viewDidLoad
}
[self.navigationController pushViewController:self.viewTwoController animated:YES];
[connection release];
}