2013-02-16 20 views
9

UżywamNSURLConnection z bloków

[NSURLConnection connectionWithRequest:req delegate:self]; 

a następnie użyć

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

obsłużyć ładowanie danych. Wszystko jest w porządku i działa bez zarzutu, ale nie podoba mi się pięknem tego Kodeksu)

I chcesz użyć bloków, aby mój kod wygląda następująco:

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

jest możliwe aby użyć NSURLConnection z Bloki?

Odpowiedz

15

Używam tej klasy:

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 

A 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 

go używać:

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

To ba sed na kod, The Big Nerd Ranch używa na swojej książce.

+0

Dziękuję jcesar, zadziałało) wielkie dzięki! – Nils

+0

To wydaje się dziwne. Jeśli wywołasz inne żądanie na twoim obiekcie, blok ukończenia może zostać nadpisany ... – Tudorizer

+0

Dzięki za pomoc. Tudorizer, musisz utworzyć nową instancję dla nowego żądania. – Segabond

-1

Mam nadzieję, że będzie to pomocne.

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

Dlaczego używasz głównej kolejki? –