NSURLConnection with blocks

前端 未结 2 905
情书的邮戳
情书的邮戳 2021-02-14 23:57

I\'m using

[NSURLConnection connectionWithRequest:req delegate:self];

and then I use

-(BOOL)connection:(NSURLConnection *)conne         


        
2条回答
  •  天涯浪人
    2021-02-15 00:34

    I use this class:

    The MyConnection.h

    #import 
    
    @interface MyConnection : NSObject  {
        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
    

    And the 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
    

    to use it:

    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];
    

    It's based on the code, The Big Nerd Ranch uses on his book.

提交回复
热议问题