私のiPhoneアプリは、HTTPポスト経由でサーバーにメッセージを送信します。いくつかの理由でNSURLConnection Delegateを利用したいと思います。NSURLConnection代理人NSURLの設定方法
ここにコードがあります。デリゲートを使用するにはどうすればよいですか?
//.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を使用していますので、私のメモリ管理について心配する必要はありません。 ;)