-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBNRConnection.m
86 lines (68 loc) · 2.54 KB
/
BNRConnection.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// BNRConnection.m
// Nerdfeed
//
// Created by THOMAS PENG on 6/24/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "BNRConnection.h"
static NSMutableArray *sharedConnectionList = nil;
@implementation BNRConnection
@synthesize request, completionBlock, xmlRootObject, jsonRootObject;
- (id)initWithRequest:(NSURLRequest *)req
{
self = [super init];
if (self) {
[self setRequest:req];
}
return self;
}
- (void)start
{
// Initialize container for data collected from NSURLConnection
container = [[NSMutableData alloc] init];
// Spawn connection
internalConnection = [[NSURLConnection alloc] initWithRequest:[self request] delegate:self startImmediately:YES];
// If this is the first connection started, create the array
if (!sharedConnectionList)
sharedConnectionList = [[NSMutableArray alloc] init];
// Add the connection to the array so it doesn't get destroyed
[sharedConnectionList addObject:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[container appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
id rootObject = nil;
// If there is a "root object"
if ([self xmlRootObject]) {
// Create a parser with the incoming data and let the root object parse its contents
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:container];
[parser setDelegate:[self xmlRootObject]];
[parser parse];
rootObject = [self xmlRootObject];
} else if ([self jsonRootObject]) {
// Turn JSON data into basic model objects
NSDictionary *d = [NSJSONSerialization JSONObjectWithData:container options:0 error:nil];
// Have the root object construct itself from basic model objects
[[self jsonRootObject] readFromJSONDictionary:d];
rootObject = [self jsonRootObject];
}
// Then, pass the root object to the completion block - remember,
// this is the block that the controller supplied.
if ([self completionBlock])
[self completionBlock](rootObject, nil);
// Now, destroy this connection
[sharedConnectionList removeObject:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// Pass the error from the connection to the completionBlock
if ([self completionBlock])
[self completionBlock](nil, error);
// Destroy this connection
[sharedConnectionList removeObject:self];
}
@end