NSHTTPURLResponse - iphone

Hey everbody, i'm trying to treat the response of a http post.
My php is giving a simple message, so, how can i treat it?
I mean, if gives me the "Error" message, do something, or "OK" do another thing.
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);
}
if (result == #"Logged") {
NSLog(#"OK");
}
if (result == #"Error") {
NSLog(#"No");
}
Thanks!

Try the isEqualToString: method. E.g.:
if ([result isEqualToString:#"Logged"]) {
NSLog(#"OK");
} else if ([result isEqualToString:#"Error"]) {
NSLog(#"No");
}

Related

exception __NSarrayM objectforkey unrecognized selector sent to instance [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
i'm trying to make login page that get data fro php file by Json. it works fine until i use this sentence [jsonData objectForKey:#"state"] , an exception appears.
i tried to make another dictonary like some answers to question before. but nothing is working with me.
Output :
Response code : 200
Resonse ==> [{"state":"true"}]
JasonData ({state = true})
Then the exception
-[__NSarrayM objectforkey:]: unrecognized selector sent to instance
i'm new to objctive-C
if you could help me.
i will be greatfull
- (IBAction)loginClicked:(id)sender
{
#try
{
if([[txtUserName text] isEqualToString:#""] || [[txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter both Username and Password" :#"Login Failed!"];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[txtUserName text],[txtPassword text]];
NSLog(#"PostData: %#",post);
NSURL *url = [NSURL URLWithString:#"http://localhost/services/pages/login.php"];
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 = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(#"%#",jsonData);
NSLog(#"%#",[jsonData objectForKey:#"state"]);
NSString *state = [(NSString*) [jsonData objectForKey:#"state"] lowercaseString ];
NSLog(#"%#", state);
if([state isEqualToString:#"true"])
{
NSLog(#"Login SUCCESS");
[self alertStatus:#"Logged in Successfully." :#"Login Success!"];
}
else
{
NSString *error_msg = (NSString *) [jsonData objectForKey:#"error_message"];
[self alertStatus:error_msg :#"Login Failed!"];
}
}
else
{
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}
}
#catch (NSException * e)
{
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#"Login Failed!"];
}
The JSON data returned by the webserive seems to be an NSArray and not NSDictionary. You can check that here,
id jsonData = [jsonParser objectWithString:responseData error:nil];
if([jsonData isKindOfClass:[NSDictionary class]]) {
NSLog(#"Dictionary");
}
else if([jsonData isKindOfClass:[NSArray class]]) {
NSLog(#"Array");
}
Your code crashes because you are assuming the parsed response as NSDictionary and passing the objectForKey: method. Being an NSArray it cannot recognise this method and raises an exception.
Now if it is an NSArray with one dictionary inside, you can read it as below,
[[jsonData objectAtIndex:0] objectForKey:#"state"];
Hope that helps!

Yet another "message sent to deallocated instance"

My app crashed (iOS/iPhone) after the execution of the following snippet:
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];
if ([urlResponse statusCode] ==500 ) {
...
}
} else {
NSLog(#"Response ==> status= %d", [urlResponse statusCode];
}
[result release];
[error release];
The code reached at the else statement, the statusCode is "0" and the code crashes with the
information that [CFError release] was sent to an deallocated instance. I commented out the
line [error release] and the crashed did not happen again. However we introduce a leak here.
What goes wrong with the error variable? Is it being used from sendSynchonousRequest?
What is the optimal way to resolve the problem?
The error object passed to an other method most not be initialized, the method you pass it on to will create the error object if an error accours. Since this method created the error object you are not the owner of that object and you are over releasing the error. The error object is created as autorelease.
Change :
NSError *error = [[NSError alloc] init];
to
NSError *error = nil;
and remove the
[error release];
Its is not necessary create error object. when you set the object to NSURLConnection, it automatic create autorelease error object. thats why your code crash, because there are also error release
try this:
NSHTTPURLResponse *urlResponse = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if ([urlResponse statusCode] ==500 ) {
...
}
} else {
NSLog(#"Response ==> status= %d", [urlResponse statusCode];
}
[result release];

not getting data from the webservice

Iam new to iphone development, i want to get data from the web service using JSON parsing here is the code
-(void)loadDataSource
{
NSString *URLPath = [NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q=Official%20Google%20Blogs"];
NSURL *URL = [NSURL URLWithString:URLPath];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
if (!error)// && responseCode == 200)
{
id res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (res && [res isKindOfClass:[NSDictionary class]])
{
self.dict=[res objectForKey:#"responseData"];
self.items = [self.dict objectForKey:#"entries"];
[self dataSourceDidLoad];
}
else
{
[self dataSourceDidError];
}
}
else
{
[self dataSourceDidError];
}
}];
}
when i run this code it displays nothing and code for collection view at index is
- (PSCollectionViewCell *)collectionView:(PSCollectionView *)collectionView viewAtIndex:(NSInteger)index
{
NSDictionary *item = [self.items objectAtIndex:index];
PSBroView *v = (PSBroView *)[self.collectionView dequeueReusableView];
if (!v)
{
v = [[PSBroView alloc] initWithFrame:CGRectZero];
}
[v fillViewWithObject:item];
return v;
}
below the code for fillViewWithObject
- (void)fillViewWithObject:(id)object
{
[super fillViewWithObject:object];
self.captionLabel.text = [object objectForKey:#"title"];
}
You apparently didn't check your error, because when I run this I get "bad URL" as the error. I also get a compiler warning, "more % conversions than arguments". That's because of the % in your url string. You shouldn't be using stringWithFormat -- just pass the literal string, and it should work:
NSString *URLPath = #"https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q=Official%20Google%20Blogs";
I see this error (or just wasted code) a lot. You shouldn't use stringWithFormat unless you are supplying a format string and arguments.

Send data to the server using for loop of HTTP POST in iPhone

I want send to the data on the server in batches.
I have to send nsmutablestring data with 25 strings at a time then get response and if the response is success then again send the next batch.
I am using HTTPConnection class.The code that I am using is like:
HttpConnectionClass * ht= [[HttpConnectionClass alloc] init];
ht.delegate=self;
ht.isNetworkIndicator = YES;
NSString *data = #"" ;
int i = 0;
self.dataforserver = [[NSMutableString alloc]init] ;
[self.dataforserver setString:#""];
for (i=0;i<= self.dataArray.count-1; i++) {
data =[NSString stringWithFormat:#"A%d%#",[[self.recordIDArray objectAtIndex:i]intValue], [self.dataArray objectAtIndex:i]];
[self.dataforserver appendString:data];
if ((i+1)%25 == 0 && i!=0 ) {
[ht makeHttpConnection:[NSString stringWithFormat:#"http://www.url.com?action=%d&subscriberid=%d&type=%#",2,56904,#"full"] withData:self.dataforserver];
NSLog(#"in for loop dataforserver is %#",dataforserver);
[dataforserver setString:#""];
}
}
if (dataforserver != #"" ) {
NSLog(#"not in for loop dataforserver is %#",dataforserver);
[ht makeHttpConnection:[NSString stringWithFormat:#"http://www.url.com?action=%d&subscriberid=%d&type=%#",2,56904,#"full"] withData:self.dataforserver];
}
I am getting response in the following method
-(void)getHttpData:(NSObject*)data isError:(BOOL)isErr errorMsg:(NSString*)err{
NSString *response=(NSString*)data;
NSLog(#"response is %#",response);
}
I want to continue the loop only if I get the response "SUCCESS".
Can anyone suggest how to achieve it.
I am very new to iOS programming.Please help
I solved this problem by using ASIHttpRequest class which is available on github.
I am posting the code that I used if anybody gets the same issue
{
NSString *data = #"" ;
int i = 0;
int batchCount =5;
NSString *type = #"full";
self.dataforserver = [[NSMutableString alloc]init] ;
[self.dataforserver setString:#""];
for (i=0;i< self.dataArray.count; i++) {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.myurl.com/gprsin?action=%d&//subscriberid=%d&type=%#",2,111,type]];
data =[NSString stringWithFormat:#"A%d%#",[[self.recordIDArray objectAtIndex:i]intValue], [self.dataArray objectAtIndex:i]];
[self.dataforserver appendString:data];
if ((i+1)%batchCount == 0 && i!=0 ) {
NSString *response = #"";
int j = 0;
while (response == #"" && j<3 ) {
//Using while loop is not necessary,I am using this because it was required to try three times till getting response.
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setPostBody:[[NSMutableData alloc] initWithData:[dataforserver dataUsingEncoding:NSUTF8StringEncoding]]];
[request setRequestMethod:#"POST"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
response = [request responseString];
NSLog(#"response is %#",response);
[dataforserver setString:#""];
}
else
{
// unable to connect show alert
NSLog(#"there is some error coming and the error is:%#",error);
return;
}
if ([response isEqualToString:#"SUCCESS"]) {
for (int k = i-batchCount+1; k<=i; k++) {
[self storeContactInDB:[self.dataArray objectAtIndex:k]:[[self.recordIDArray objectAtIndex:k]intValue]];//if you want to store contacts in database along only after successfully sending it to server
}
type = #"INCREMENT";
}
else if ([response isEqualToString:#"FAIL"])
{
//show alert
return;
}
j++;
}
}
if (dataforserver != #"" && i== self.dataArray.count-(self.dataArray.count%batchCount) )
{
NSString *response = #"";
int j = 0;
while (response == #"" && j<3 ) {
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setPostBody:[[NSMutableData alloc] initWithData:[dataforserver dataUsingEncoding:NSUTF8StringEncoding]]];
[request setRequestMethod:#"POST"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
response = [request responseString];
NSLog(#"response is %#",response);
}
else
{
// unable to connect show alert
NSLog(#"there is some error coming and the error is:%#",error);
return;
}
if ([response isEqualToString:#"SUCCESS"]) {
for (i = self.dataArray.count-(self.dataArray.count%batchCount); i<self.dataArray.count; i++)
{
[self storeContactInDB:[self.dataArray objectAtIndex:i]:[[self.recordIDArray objectAtIndex:i]intValue]];
}
type = #"INCREMENT";
}
else if ([response isEqualToString:#"FAIL"])
{
//show alert
return;
}
j++;
}
}
}
}

[parser setDelegate:self];

NSString* username = [[NSUserDefaults standardUserDefaults] stringForKey:#"username_preference"];
NSString* accountPassword = [[NSUserDefaults standardUserDefaults] stringForKey:#"password_preference"];
NSString* urlString = [NSString stringWithFormat:#"https://%#:%##testing.com/test.php",username,accountPassword];
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
int status = [httpResponse statusCode];
if (!((status >= 200) && (status < 300))) {
NSLog(#"Connection failed with status %#", status);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
} else {
NSXMLParser* xmlparser = [[NSXMLParser alloc] initWithData: response];
NSLog(#"at parser %#", xmlparser);
[parser setDelegate:self];
The last line of the code is showing me error and suggest that "change parser to pause"!! Please help!!
Well, isn't that because your parser variable is named 'xmlparser' and not 'parser' ?
Change parser to xmlparser.