NSURLConnection与块

时间:2013-02-16 19:53:06

标签: nsurlconnection objective-c-blocks

我正在使用

[NSURLConnection connectionWithRequest:req delegate:self];

然后我用

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
-(void)connectionDidFinishLoading:(NSURLConnection *)connection;

处理数据加载。一切都很好,工作正常,但我不喜欢这段代码的美丽)

我希望使用块,使我的代码看起来像这样:

[myConnection sendData:data 
          successBlock:^(void){NSLog(@"success");}
            errorBlock:^(NSError * error){NSLog(@"error.description: %@", error.description);}];

是否可以将NSURLConnection与块一起使用?

2 个答案:

答案 0 :(得分:16)

我使用这个类:

MyConnection.h

#import <Foundation/Foundation.h>

@interface MyConnection : NSObject <NSURLConnectionDelegate, NSURLConnectionDataDelegate> {
    NSURLConnection * internalConnection;
    NSMutableData * container;
}

-(id)initWithRequest:(NSURLRequest *)req;

@property (nonatomic,copy)NSURLConnection * internalConnection;
@property (nonatomic,copy)NSURLRequest *request;
@property (nonatomic,copy)void (^completitionBlock) (id obj, NSError * err);


-(void)start;

@end

MyConnection.m

#import "MyConnection.h"

static NSMutableArray *sharedConnectionList = nil;

@implementation MyConnection
@synthesize request,completitionBlock,internalConnection;

-(id)initWithRequest:(NSURLRequest *)req {
    self = [super init];
    if (self) {
        [self setRequest:req];  
    }
    return self;
}

-(void)start {

    container = [[NSMutableData alloc]init];

    internalConnection = [[NSURLConnection alloc]initWithRequest:[self request] delegate:self startImmediately:YES];

    if(!sharedConnectionList)
        sharedConnectionList = [[NSMutableArray alloc] init];
    [sharedConnectionList addObject:self];

}


#pragma mark NSURLConnectionDelegate methods

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [container appendData:data];

}

//If finish, return the data and the error nil
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

    if([self completitionBlock])
        [self completitionBlock](container,nil);

    [sharedConnectionList removeObject:self];

}

//If fail, return nil and an error
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    if([self completitionBlock]) 
        [self completitionBlock](nil,error);

    [sharedConnectionList removeObject:self]; 

}

@end

使用它:

MyConnection * connection = [[MyConnection alloc]initWithRequest:req];
[connection setCompletitionBlock:^(id obj, NSError *err) {

            if (!err) {
                 //It's ok, do domething with the response data (obj)                  
            } else {
                //There was an error
            } 

        }];
[connection start];

它基于代码,The Big Nerd Ranch在他的书中使用。

答案 1 :(得分:-1)

我希望它会有所帮助。

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                           NSLog(@"%@", response);
                           NSLog(@"%@", data);
                       }];