Mon application iPhone envoie un message à un serveur via un message HTTP. Je voudrais utiliser le délégué NSURLConnection pour plusieurs raisons.Comment définir le délégué NSURLConnection pour NSURL
Voici le code. Que dois-je faire pour l'utiliser avec un délégué?
//.h
#import <Foundation/Foundation.h>
@interface ServerConnection : NSObject <NSURLConnectionDelegate>
-(NSData*) postData: (NSString*) strData;
//delegate method
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
@end
et la .m (la partie importante est la deuxième méthode)
//.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
Encore une fois, la question est ce que dois-je faire pour le faire utiliser un délégué? J'ai besoin de savoir quand j'en ai fini avec la connexion.
En guise de remarque, j'utilise ARC pour ne pas vous soucier de ma gestion de la mémoire. ;)