-
Notifications
You must be signed in to change notification settings - Fork 6
/
MVJSONGetRequest.m
93 lines (77 loc) · 2.47 KB
/
MVJSONGetRequest.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
87
88
89
90
91
92
93
#import "MVJSONGetRequest.h"
@interface MVJSONGetRequest () <NSURLConnectionDelegate>
@property (strong, readwrite) NSURL *url;
@property (strong, readwrite) NSURLConnection *urlConnection;
@property (strong, readwrite) NSMutableData *mutableData;
@property (strong, readwrite) void(^callbackBlock)(NSObject *json);
@end
@implementation MVJSONGetRequest
@synthesize url = url_,
urlConnection = urlConnection_,
mutableData = mutableData_,
callbackBlock = callbackBlock_;
- (id)initWithURL:(NSURL*)url
{
self = [super init];
if(self)
{
url_ = url;
urlConnection_ = nil;
mutableData_ = nil;
callbackBlock_ = nil;
}
return self;
}
- (void)get:(void(^)(NSObject *json))block
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:self.url];
[req setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[req setHTTPMethod:@"GET"];
[req setAllHTTPHeaderFields:[NSDictionary dictionaryWithObjectsAndKeys:
@"application/json", @"Accept",
nil]];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:req
delegate:self];
if (!self.urlConnection)
{
block(nil);
}
else
{
self.callbackBlock = block;
self.mutableData = [[NSMutableData alloc] init];
CFRunLoopRun();
}
});
}
#pragma mark -
#pragma mark NSURLConnectionDelegate Methods
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
dispatch_async(dispatch_get_main_queue(), ^{
self.callbackBlock(nil);
});
CFRunLoopStop(CFRunLoopGetCurrent());
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.mutableData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;
NSObject *json = [NSJSONSerialization JSONObjectWithData:self.mutableData
options:0
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
self.callbackBlock(json);
});
CFRunLoopStop(CFRunLoopGetCurrent());
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}
@end