code_junkie

Managing multiple asynchronous NSURLConnection connections

Nov 12th, 2011
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
  2. delegate:self];
  3.  
  4. connectionToInfoMapping =
  5. CFDictionaryCreateMutable(
  6. kCFAllocatorDefault,
  7. 0,
  8. &kCFTypeDictionaryKeyCallBacks,
  9. &kCFTypeDictionaryValueCallBacks);
  10.  
  11. CFDictionaryAddValue(
  12. connectionToInfoMapping,
  13. connection,
  14. [NSMutableDictionary
  15. dictionaryWithObject:[NSMutableData data]
  16. forKey:@"receivedData"]);
  17.  
  18. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  19. {
  20. NSMutableDictionary *connectionInfo =
  21. CFDictionaryGetValue(connectionToInfoMapping, connection);
  22. [[connectionInfo objectForKey:@"receivedData"] appendData:data];
  23. }
  24.  
  25. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  26. if (connection == self.savingConnection) {
  27. [self.savingReturnedData appendData:data];
  28. }
  29. else {
  30. [self.sharingReturnedData appendData:data];
  31. }
  32. }
  33.  
  34. // This variable must be able to be referenced from - (void)connectionDidFinishLoading:(NSURLConnection *)connection
  35. NSMutableDictionary *connDictGET = [[NSMutableDictionary alloc] init];
  36. //...//
  37.  
  38. // You can use any object that can be referenced from - (void)connectionDidFinishLoading:(NSURLConnection *)connection
  39. [connDictGET setObject:anyObjectThatCanBeReferencedFrom forKey:[aConnectionInstanceJustInitiated description]];
  40. //...//
  41.  
  42. // At the delegate method, evaluate if the passed connection is the specific one which needs to be handled differently
  43. if ([[connDictGET objectForKey:[connection description]] isEqual:anyObjectThatCanBeReferencedFrom]) {
  44. // Do specific work for connection //
  45.  
  46. }
  47. //...//
  48.  
  49. // When the connection is no longer needed, use (NSString *)description as key to remove object
  50. [connDictGET removeObjectForKey:[connection description]];
  51.  
  52. NSMutableDictionary* dict = [NSMutableDictionary dictionary];
  53. NSValue *key = [NSValue valueWithNonretainedObject:aConnection]
  54. /* store: */
  55. [dict setObject:connInfo forKey:key];
  56. /* lookup: */
  57. [dict objectForKey:key];
Add Comment
Please, Sign In to add comment