-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathResponseLoader.m
95 lines (73 loc) · 2.34 KB
/
ResponseLoader.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
94
95
//
// ResponseLoader.m
// Jayson
//
// Created by Ben Yellin on 12/22/10.
// Copyright 2010 Been Yelling. All rights reserved.
//
#import "ResponseLoader.h"
@interface ResponseLoader (Private)
- (void)beginDownload;
- (Response *)responseFromData:(NSData *)data;
@end
@implementation ResponseLoader
@synthesize delegate;
- (id)initWithURL:(NSURL *)aURL {
if (self = [super init]) {
url = [aURL copy];
responseData = nil;
}
return self;
}
- (void)dealloc {
[url release];
[responseData release];
[super dealloc];
}
- (void)start {
[self beginDownload];
}
- (void)beginDownload {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
responseData = [[NSMutableData alloc] init];
[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
}
- (Response *)responseFromData:(NSData *)data {
NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
Response *resp = [[Response alloc] init];
resp.source = [dataStr copy];
kResponseType predictedType = DEFAULT_RESPONSE_TYPE;
NSRange jsonRange = [[mimeType lowercaseString] rangeOfString:@"json"];
if (jsonRange.location != NSNotFound)
predictedType = kResponseJSON;
NSRange xmlRange = [[mimeType lowercaseString] rangeOfString:@"xml"];
if (xmlRange.location != NSNotFound)
predictedType = kResponseXML;
resp.responseType = predictedType;
[dataStr release];
return resp;
}
#pragma mark NSURLConnection Stuuuuff
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
if ([delegate respondsToSelector:@selector(responseLoaderDidBegin:)]) {
[delegate responseLoaderDidBegin:self];
}
mimeType = [response MIMEType];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if ([delegate respondsToSelector:@selector(responseLoader:didFailWithError:)]) {
[delegate responseLoader:self didFailWithError:error];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
if ([delegate respondsToSelector:@selector(responseLoader:didFinishWithResponse:)]) {
[delegate responseLoader:self didFinishWithResponse:[self responseFromData:responseData]];
}
[responseData release];
}
@end