2014-01-21 27 views
1

我想讓我自己的請求類,我打算在整個我的應用程序中使用。這是我到目前爲止提出的代碼。NSURLConnectionDelegate在一個函數中回調

-(IIWRequest *)initAndLaunchWithDictionnary:(NSDictionary *)dictionnary 
{ 
    self=[super init]; 
    if (self) { 
     // Create the request. 
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxxxx.com/app/"]]; 

     // Convert data 
     SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init]; 
     NSString *jsonData = [jsonWriter stringWithObject:dictionnary]; 
     NSLog(@"jsonData : %@",jsonData); 
     NSData *requestData = [jsonData dataUsingEncoding: NSUTF8StringEncoding]; 
     request.HTTPBody = requestData; 

     // This is how we set header fields 
     [request setHTTPMethod:@"POST"]; 
     [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
     [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"]; 
     [request setHTTPBody: requestData]; 

     // Create url connection and fire request 
     NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; 
     [self activateNetworkActivityIndicator]; 
     if (connection) { 
      NSLog(@"Connection"); 
     } else { 
      NSLog(@"No connection"); 
     } 
    } 
    return self; 
} 

我已經包含NSURLConnectionDelegate。我想發起連接回調,例如完成或者回退到之前提到的功能。所有這一切的目標是隻得到一個方法調用到底看起來像這樣:

-(IIWRequest *)initAndLaunchWithDictionnary:(NSDictionary *)dictionary inBackgroundWithBlock:^(BOOL succeeded){} 

任何想法?謝謝 !

回答

1

使用塊的方法會降低你的功能,以及sendAsynchronousRequest:queue:completionHandler:

閱讀本doc

+0

謝謝!這就是我一直在尋找的! –

0

如果您使用的是iOS的7,我推薦了很多你使用NSURLSession類,這種新的網絡API,真是太神奇了,簡單。

無論如何,爲了回答你的問題,你只需要在你的類中保存回調的引用,並在你收到服務器的響應時調用它。

保持參考,你可以做這樣的事情:

// in your .h file 
typedef void (^ResponseBlock)(BOOL success); 

// in your .m, create a class extension and put declare the block to use it for callback 
@interface MyClass() 
{ 
    ResponseBlock callback; 
} 

// You can store reference using equal like this 
- (void)myMethodRequestWithResponseBlock:(ResponseBlock)responseBlock 
{ 
    callback = responseBlock; 
    // statements 
} 

// And finally, you call back block simple like this: 
callback(success); 

再次使用NSURLSession API,如果你能,你將簡化您的工作。

我希望這可以幫助你。 乾杯! NSURLConnection的類

相關問題