我的iPhone應用程序通過HTTP發送消息到服務器。我想利用NSURLConnection委託有以下幾個原因。如何設置NSURL的NSURLConnection代理
這是代碼。我應該怎樣做才能使用委託?
//.h
#import <Foundation/Foundation.h>
@interface ServerConnection : NSObject <NSURLConnectionDelegate>
-(NSData*) postData: (NSString*) strData;
//delegate method
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
@end
與.m(重要的部分是第二個方法)
//.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
同樣,問題是我應該怎麼做,使之使用委託?我需要知道我何時完成連接。
作爲一個便箋,我使用ARC,因此您不必擔心我的內存管理問題。 ;)