My iPhone app sends a message to a server via HTTP post. I would like to make use of the NSURLConnection Delegate for several reasons.
Here is the code. What should I do to make it use a delegate?
//.h
#import <Foundation/Foundation.h>
@interface ServerConnection : NSObject <NSURLConnectionDelegate>
-(NSData*) postData: (NSString*) strData;
//delegate method
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
@end
and the .m (the important part is the second method)
//.m
#import "ServerConnection.h"
@implementation ServerConnection
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
-(NSData*) postData: (NSString*) strData //it's gotta know what to post, nawmean?
{
//postString is the STRING TO BE POSTED
NSString *postString;
//this is the string to send
postString = @"data=";
postString = [postString stringByAppendingString:strData];
NSURL *url = [NSURL URLWithString:@"//URL GOES HERE"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];
//setting prarameters of the POST connection
[request setHTTPMethod:@"POST"];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:@"Content-Length"];
[request addValue:@"en-US" forHTTPHeaderField:@"Content-Language"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setTimeoutInterval:20.0];
NSLog(@"%@",postString);
NSURLResponse *response;
NSError *error;
//this sends the information away. everybody wave!
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
return urlData;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
//delegate
{
NSLog(@"connectionDidFinishLoading!!!");
}
@end
Again, the question is what should I do to make it use a delegate? I need to know when I am done with the connection.
As a side note, I’m using ARC so you don’t worry about my memory management. 😉
You’re using the synchronous API, so when the method returns the connection has already finished. You only need the delegate if you’re using the asynchronous API which you can use with any of
+connectionWithRequest:delegate:,–initWithRequest:delegate:, or–initWithRequest:delegate:startImmediately:.