如何设置NSURL的NSURLConnection代理

问题描述:

我的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,因此您不必担心我的内存管理问题。 ;)

您使用的是同步API,所以当该方法返回已经完成连接。如果您使用异步API,则只需要代理人,您可以使用任何+connectionWithRequest:delegate:–initWithRequest:delegate:–initWithRequest:delegate:startImmediately:中的任何一个。

sendSynchronousRequest方法:不使用委托。

在connectionWithRequest看看:委托: