Problem with NSHTTPCookie - iphone

I want to make login application. My first screen login form with two text fields and one button. When I pres this button I invoke one method that invoke this method:
- (int)login {
// Add data to post request
NSHTTPURLResponse * response;
NSString *myRequestString = [[NSString alloc] initWithFormat:#"userdata='%#'&passdata='%#'",
username.text, password.text];
NSError * error;
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request;
request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://server.com/login.php"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] autorelease];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: myRequestData];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:#"http://server.com/login.php"]];
//int cid;
for (NSHTTPCookie *cookie in all) {
NSLog(#"Name: %# : Value: %#", cookie.name, cookie.value);
// cid = (int)cookie.value;
}
// NSLog(#"id: %d",cid);
[myRequestString release];
[request release];
return 1;
}
When I pres this button my program crash and next to this row:
NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:#"http://sms.britecs.com/login.php"]];
i have Thread1: Program received signal: "EXC_BAD_ACCESS" but don't know how to fix it.
I have one more question. How can I use this cookies in my next screen?
Thanks

With [request release]; you are releasing an autoreleased object. Don't do that, it'll be released the next run loop cycle by the autorelease pool. Remove the autorelease at the end of the initialization and you are fine, else remove the release statement.
Here you are creating it:
request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://server.com/login.php"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] autorelease]; // <---

Related

newby IOS: unable to redirect url

This is my first IOS project. Having a tough time getting login to work. The site has a meta_refresh to another url. I've tried to send another request to the url in the meta_refresh but then the app just hangs. I'm sure that I'm doing something wrong but I'm using XCode 4.4 so a lot of the NSURLConnection delegate methods have been deprecated.
Here's what I'm doing:
NSString *urlAsString = baseURL;
urlAsString = [urlAsString stringByAppendingString:#"?user[login]=username"];
urlAsString = [urlAsString stringByAppendingString:#"&user[password]=password"];
urlAsString = [urlAsString stringByAppendingString:#"&origin=splash"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"POST"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if([data length] > 0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
NSRange obj = [html rangeOfString:#"http-equiv=\"refresh\""];
NSInteger len = obj.length;
} else if([data length] == 0 && error == nil) {
NSLog(#"No data was returned.");
} else {
NSLog(#"Error happened = %#", error);
}
Here's what I'm getting:
Another question is that I've read that I should use asynchronous connection. The trouble is that I need the data scraped from the site to display on the screen. If I display the screen before the data is returned, then I won't have any data -- or am I not understanding how this works?
Thanks.
--Tony
I think that maybe you're a mixing stuff. You're setting a string url with GET values and then you set the HTTPMethod to POST and I don't know if that is going to work fine.
Here's a code that I have to send values with POST:
NSString *post = [NSString stringWithFormat:#"&user_login=%#&user_password=%#&origin=%#,username,password, splash];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:baseURL]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

My app logs in twice with a URLRequest

When i press login in my app, it logs in twice in API instead of just once.., there is something wrong with this but i cant find what, because it just execute this code once.
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
NSHTTPURLResponse * response;
NSError * error;
NSMutableURLRequest * request;
NSString * params;
NSString *urlAddress = [NSString stringWithFormat:#"%#/?action=request&api=json&module=ManagementModule&function=startSession&instance=0",[ConnectServer returnserverip]];
NSLog(#"UPX %#",[ConnectServer returnserverip]);
NSLog(#"IP %#",[ConnectServer returnclientip]);
if([defaults boolForKey:#"enablePincode"]){
NSString *account = [defaults stringForKey:#"myAccount"];
NSString *username =[defaults stringForKey:#"myUsername"];
NSString *password = [defaults stringForKey:#"myPassword"];
NSString *clientip = [ConnectServer returnclientip];
NSString *clientname = [ConnectServer returnclientname];
params = [[[NSString alloc] initWithFormat:#"params=&auth[password]=%#&auth[mode]=%#&auth[account]=%#&auth[user]=%#&auth[rights]=%#&auth[user_ip]=%#&auth[client_name]=%#",password,#"password",account,username,#"user",clientip,clientname] autorelease];
}
else {
NSString *clientip = [ConnectServer returnclientip];
NSString *clientname = [ConnectServer returnclientname];
params = [[[NSString alloc] initWithFormat:#"params=&auth[password]=%#&auth[mode]=%#&auth[account]=%#&auth[user]=%#&auth[rights]=%#&auth[user_ip]=%#&auth[client_name]=%#",[myPassword text],#"password",[myAccount text],[myUsername text],#"user",clientip,clientname] autorelease];
}
request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlAddress] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60] autorelease];
NSData *myRequestData = [params dataUsingEncoding:NSUTF8StringEncoding];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[[NSURL URLWithString: urlAddress] host]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:myRequestData];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [myRequestData length]] forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"RESPONSE HEADERS: \n%#", [response allHeaderFields]);
request.URL = [NSURL URLWithString:urlAddress];
error = nil;
response = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"The server saw:\n%#", [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease]);
NSLog(#"Parameters: %#", params);
NSLog(#"Actual sended parameters to the server: %#", myRequestData);
NSString *Sresponse;
Sresponse = [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease];
There are two requests in the code:
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
and five lines down
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Hint: In cases like this use wireshark or my favorite Charles which will decode SSL connections.
I guess it is possible. I mean, I am running APEX at this very moment and I have the same app. running in 3 different windows under the same user without having to log on. The only time I have to log on is when I change user.
So yes, it is possible, but not sure why it is not working at your end. Could it be that you run both development and runtime at the same time using different users? Because if one of the APEX users differs from the other then you are prompted to log on again with the other user.

iPhone App crashing - viewDidLoad

My iphone app crashes when I add a method to the viewDidLoad in my main viewcontroller:
#import "dbQuestionGetterViewController.h"
#import "dbConnector.h";
#implementation dbQuestionGetterViewController
#synthesize questions;
-(void)viewDidLoad{
//code to initialise view
NSDictionary* arr = [dbConnector getQuestions:2 from:#"http://dev.speechlink.co.uk/David/get_questions.php"];
questions = arr;
[arr release];
[super viewDidLoad];
}
I'm calling a static method from the dbConnector class, but it crashes before even loading..
The method in dbConnector:
//method to
+(NSDictionary*)getQuestions:(NSInteger)sectionId from: (NSString*) url{
//connect to database given by url
//NSError *error = nil;
//NSURLResponse *response = nil;
NSMutableString* myRequestString = [[NSMutableString string]initWithFormat:#"section=%#", sectionId];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: url]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPMethod: #"POST"];
//post section
[request setHTTPBody: myRequestData];
//store them in the dictionary
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *questions = [json objectFromJSONString];
[json release];
[request release];
return [questions autorelease];
}
what am i doing wrong?
First of all, you're not doing anything with this code:
NSMutableString* myRequestString = [[NSMutableString string]initWithFormat:#"section=%#", sectionId];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: url]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPMethod: #"POST"];
//post section
[request setHTTPBody: myRequestData];
Remove it.
Secondly, questions is already autoreleased.
NSDictionary *questions = [json objectFromJSONString]; // < autoreleased
So simply doing return questions; should work.
This also means that you should not under any case release this returned value. Thus, get rid of this:
[arr release];
The NSDictionary that is returned from the static method is autoreleased. But you release it in the viewDidLoad method.
You are releasing the arr object that getQuestions returns. Since you've already marked this object as autorelease you don't need to explicitly release it yourself. Remove the following line from viewDidLoad and you should be set:
[arr release];
Also, your myRequestString is suspect. You are calling the string class method, which returns a fully allocated and initialized string, but then you're calling initWithFormat on it, which is normally for strings you've just alloc-ed. Replace that line with:
[[NSMutableString alloc]initWithFormat:#"section=%#", sectionId]
and then release it right after your [request release].

How to send a Get request in iOS?

I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as
[requestObject setHTTPMethod:#"GET"];
Tell me what could be the problem. Also provide me the code if you have.
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL
URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: #"GET"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response1 =
[NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError];
NSString *getString = [NSString stringWithFormat:#"parameter=%#",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getLength = [NSString stringWithFormat:#"%d", [getData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https:yoururl"]];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:getData];
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSAssert(self.urlConnection != nil, #"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
Make sure your requestObject is of type NSMutableURLRequest.
Simply call and use:
(void)jsonFetch{
NSURL *url = [NSURL URLWithString:#"http://itunes.apple.com/us/rss/topaudiobooks/limit=10/json"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *data = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSError *erro = nil;
if (data!=nil) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&erro ];
if (json.count > 0) {
for(int i = 0; i<10 ; i++){
[arr addObject:[[[json[#"feed"][#"entry"] objectAtIndex:i]valueForKeyPath:#"im:image"] objectAtIndex:0][#"label"]];
}
}
}
dispatch_sync(dispatch_get_main_queue(),^{
[table reloadData];
});
}];
[data resume];
}

Sending form data via HTTP Post [Objective C]

I have a form data from an iphone app that needs to send HTTP Post variables to a URL.
The thing is, I've been told not to use setHTTPBody, but am unsure of how else to do it as every example I see uses setHTTPBody; even those that use POST methods.
To make things matters a little more complicated, the URL/webpage requires a submit=true and action=enquiry in the post variables.
Here's what I have so far.
NSString *formContactName = [self contactName];
NSString *formEmail = [self email];
NSString *formPhone = [self phone];
NSString *formComments = [self comments];
// The above data is fine, as explored here.
NSLog(#"formContactName = %#", formContactName);
NSLog(#"formEmail = %#", formEmail);
NSLog(#"formPhone = %#", formPhone);
NSLog(#"formComments = %#", formComments);
// Setup request
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:advertURL]];
[request setHTTPMethod:#"POST"];
// set headers
NSString *contentType = [NSString stringWithFormat:#"text/plain"];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
// setup post string
NSMutableString *postString = [[NSMutableString alloc] init];
[postString appendFormat:#"contactname=%#", formContactName];
[postString appendFormat:#"&email=%#", formEmail];
[postString appendFormat:#"&phone=%#", formPhone];
[postString appendFormat:#"&comments=%#", formComments];
[postString appendFormat:#"&submit=yes"];
[postString appendFormat:#"&action=enquiry"];
// I've been told not to use setHTTPBody for post variables, but how else do you do it?
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
// get response
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >=200 && [urlResponse statusCode] <300)
{
NSLog(#"Response ==> %#", result);
}
[result release];
[error release];
I always get a 200 result, which is good. But the response back indicates that the Post variables are not getting through.
The response back has a field in it called "enquirysent" and its always blank. If the Post variables are successful, it should return a "1" or true statement.
"enquirysent": ""
Therefore, my question is: How do I force the HTTP-POST variables in the above request?
Thanks.
you can use ASIHTTPRequest to simplify:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"Ben" forKey:#"first_name"];
[request setPostValue:#"Copsey" forKey:#"last_name"];
[request setFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photo"];