开发者

How to get an Answer from a web service after sending Get request in iOS

I'm a novice in iOS developing, and have some problems with understanding web service organization. I want to send a Get query to the URL. And I do it开发者_StackOverflow中文版 so:

-(BOOL) sendLoginRequest{
NSString *getAction = [NSString stringWithFormat:@"action=%@&username=%password=%@",@"login",self.log.text, self.pass.text];
NSString *getUserName = [NSString stringWithFormat:@"username=%@",self.log.text];
NSString *getPassword = [NSString stringWithFormat:@"username=%@",self.pass.text];

NSData *getDataAction = [getAction dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *getLengthAction = [NSString stringWithFormat:@"%d", [getDataAction length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

[request setURL:[NSURL URLWithString:@"http:http://www.site.fi/api/"]];

[request setHTTPMethod:@"GET"];

[request setValue:getLengthAction forHTTPHeaderField:@"Content-Length"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:getLengthAction];

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;
}

the answer may be "true" or "false"

but how can I take this answer?


You should define next methods to get answer:

  1. Start connection: [self.urlConnection start];

  2. Check server response:

    - (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response

  3. Collect data that servers sends you:

    - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data

  4. Be sure to manage errors:

    - (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error

  5. Check received data:

    - (void)connectionDidFinishLoading:(NSURLConnection *)theConnection

To be more sure that you correctly understood me check NSURLConnection Class Reference


Send [self.urlConnection start]; and implement the NSURLConnectionDelegate methods to receive the response. Alternatively use ASIHTTPRequest and the block handlers, which to my way of thinking are much easier to write for beginners, provided you don't need to run on iOS pre-4.1.

You will gather the data returned as NSData; just convert that to a string, and either call boolValue on the string (check the docs for its rather strange tests), or use a specific set of your own tests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜