Updating UI from callback function - objective-c

I'm performing asynchronous request with ASI HTTP Request and I want to update Textbox with new information from the request, so I'm updating it from callback function.
Here is my code so far:
Second Class
- (void)Login {
NSLog(#"Login");
NSURL *url = [NSURL URLWithString:#"http://ts5.travian.sk/login.php"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:#selector(loginRequestFinished:)];
[request setDidFailSelector:#selector(loginRequestFailed:)];
[request startAsynchronous];
}
- (void)loginRequestFinished:(ASIHTTPRequest *)request
{
NSLog(#"Completed!");
NSString *response = [request responseString];
AppController *ac = [AppController getInstance];
[ac.textbox performSelectorOnMainThread:#selector(setStringValue:) withObject:response waitUntilDone:NO];
}
AppController is a main class. Setting text from there is working. But this code isnt doing anything. It just wrote 2 log lines to debug window.
Am I missing something?

Related

How to stop UIWebView loading immediately

As ios documentation says, [webView stopLoading] method should be used in order to stop webview load task.
As far as I see, this methods runs asynchronously, and does NOT stop currently processing load request immediately.
However, I need a method which will force webview to immediately stop ongoing task, because loading part blocks the main thread, which could result in flicks on animations.
So, is there a way to succeed this?
This worked for me.
if (webText && webText.loading){
[webText stopLoading];
}
webText.delegate=nil;
NSURL *url = [NSURL URLWithString:#""];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webText loadRequest:requestObj];
Don't use the UIWebView to download your html document directly.
Use async download mechanism like ASIHTTPRequest to get your html downloaded by a background thread.
When you get the requestFinished with a content of your html then give it to the UIWebView.
Example from the ASIHTTPRequest's page how to create an asynchronous request:
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
} 
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
 
// Use when fetching binary data
NSData *responseData = [request responseData];
}  
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
Use the responseString to your UIWebView's loadHTMLString method's parameter:
UIWebView *webView = [[UIWebView alloc] init];
[webView loadHTMLString:responseString baseURL:[NSURL URLWithString:#"Your original URL string"]];

Calling Webservice in iPhone application?

I am using soap webservice.
In that i am calling one webmethod. Here if i call from one part of my code is working fine and calling service successfully and retriving data successfully.
But if i calling same method from another part of code of same class is not responding and not getting any data from service. Why is going like that can any one help me please.
Thanks in advance
In detail.m
-(void) downloadAndParse:(NSMutableURLRequest *)sentReq {
conn = [[NSURLConnection alloc] initWithRequest:sentReq delegate:self];
if (conn) {
webData = [[NSMutableData data] retain];
}
}
-(void)fullBarcodeSearch:(NSString *)code {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
URLRequest *r = [[URLRequest alloc] init];
NSMutableURLRequest *req = [r fullBarcodeSearch:code];
[r release];
[self downloadAndParse:req];
}
In URLRequest.m
-(NSMutableURLRequest *) addHeaderToSoapXML:(NSString *) soapMsg {
NSURL *url = [NSURL URLWithString:str];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d",[soapMsg length]];
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"content-type"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
return req;
}
if service not called then i am getting error like this
*oid _WebThreadLockFromAnyThread(bool), 0x6958130: Obtaining the web lock from a thread other than the main thread or the web thread. UIKit should not be called from a secondary thread.*
Please any one help me
Thanks in advance
You need an NSURLConnection to execute the NSURLRequest. Lookup the Apple Docs on the class.
Something like:
[urlConnection sendSynchronousRequest:urlRequest returningResponse: &urlResponse error:&error]

POST with NSURLConnection - NO JSON

I am trying to write an iPhone app in Objective-C. I need to POST data using NSURLConnection. Every example I can find deals with JSON; I do not need to use JSON. All I need to do is POST the data and get a simple 1 or 0 (succeed or fail) from a PHP script. Nothing more.
I came across this code but I am not sure how to use it or modify it to not use JSON:
- (void)performRequest {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://someplace.com/"]];
[request setValue:#"Some Value" forHTTPHeaderField:#"Some-Header"];
[request setHTTPBody:#"{\"add_json\":\"here\"}"];
[request setHTTPMethod:#"POST"];
[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Fail..
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Request performed.
}
Here's how to create an ordinary post.
First create a request of the right type:
NSURL *URL = [NSURL URLWithString:#"http://example.com/somepath"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
Now format your post data as a URL-encoded string, like this:
NSString *params = #"param1=value1&param2=value2&etc...";
Remember to encode the individual parameters using percent encoding. You can't entirely rely on the NSString stringByAddingPercentEscapesUsingEncoding method for this (google to find out why) but it's a good start.
Now we add the post data to your request:
NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
[request addValue:#"8bit" forHTTPHeaderField:#"Content-Transfer-Encoding"];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:[NSString stringWithFormat:#"%i", [data length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:data];
And that's it, now just send your request as normal using NSURLConnection (or whatever).
To interpret the response that comes back, see Maudicus's answer.
You can use the following NSURLConnection method if you target ios 2.0 - 4.3 (It seems to be deprecated in ios 5)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString * string = [[NSString alloc] initWithData:data encoding:
NSASCIIStringEncoding];
if (string.intValue == 1) {
} else {
}
}
I've a very similar situation to whitebreadb. I'm not disagreeing with the answers submitted and accepted but would like to post my own as the code provided here didn't work for me (my PHP script reported the submitted parameter as a zero-length string) but I did find this question that helped.
I used this to perform a posting to my PHP script:
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.myphpscriptlocation.net/index.php?userID=%#",self.userID_field.stringValue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
NSURLConnection *c = [NSURLConnection connectionWithRequest:request delegate:self];

How to pass additional parameters to ASIHTTPRequest didFinishSelector selector

Im building api for our rest api using ASIHTTPRequest.
Api wraps all requests to its own methods.
- (void) foo:(id)caller
andSuccessCallback:(SEL)successCallback
andFailureCallback:(SEL)failureCallback {
_currentCaller=caller;
_currentSuccessCallback=successCallback;
_currentFailureCallback=failureCallback;
NSString *urlString = #"http://localhost/foo";
NSURL *url= [NSURL URLWithString: urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:#selector(fooSuccess:)];
[request startAsynchronous];
}
- (void) fooSuccess:(ASIHTTPRequest *)request {
if (statusCode >=400) {
if ([_currentCaller respondsToSelector:_currentFailureCallback])
[_currentCaller performSelector:_currentFailureCallback withObject:statusCode withObject:message];
} else {
if ([_currentCaller respondsToSelector:_currentSuccessCallback])
[_currentCaller performSelector:_currentSuccessCallback];
}
[request release];
}
Currently to pass callback selector I use class private variables _currentCaller _currentSuccessCallback _currentFailureCallback=failureCallback
Can i pass them to fooSuccess callback directly?
You can pass objects by populating a NSDictionary and setting it as the request's userInfo property.

NSURLConnection POST also calls GET of same URL

I have a NSURLConnection which is a post to the server, but I expect it to return some small data, whether it was successful or not.
-(void)submitPost:(NSString *)xml
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[service generateURL]];
NSString *result = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)xml, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8);
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[result dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
NSLog(#"Connection success");
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[theConnection retain];
failed = NO;
}
else
{
NSLog(#"Connection failed");
}
}
The problem is, not only does it send a post the URL, it also sends a GET, and the GET response is returned as the data... I'm a bit confused. I checked my wireshark output, and it's definitely making both a post and a get.
What do you guys think?
Does the URL respond to a POST with redirect? You can implement the NSURLConnection delegate method connection:willSendRequest:redirectResponse: to see if that's the case (and to cancel an unwanted redirect).