-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceController.j
More file actions
110 lines (96 loc) · 2.46 KB
/
ServiceController.j
File metadata and controls
110 lines (96 loc) · 2.46 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
@import <Foundation/CPObject.j>
//// This is a helper class for handling JSON web services
@implementation ServiceController : CPObject
{
CPURLConnection connection;
CPURLConnection queuedConnection;
CPString endpoint;
id delegate;
CPString data;
}
+ (id)serviceWithURL:(CPString)path startPostWithObject:(id)obj delegate:(id)del
{
var ret = [[ServiceController alloc] initWithEndPoint:""];
[ret setDelegate:del];
[ret post:path withData:obj];
return ret;
}
- (id)initWithEndPoint:(CPString)e
{
self = [super init];
if (self) {
data = "";
endpoint = e;
}
return self;
}
- (void)connection:(CPURLConnection)c didFailWithError:(id)error
{
if ([delegate respondsToSelector:@selector(serviceDelegate:failedWithError:)]) {
[delegate serviceDelegate:self failedWithError:error];
}
}
//-(void)connection:(CPURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response;
- (void)connection:(CPURLConnection)c didReceiveData:(CPString)d
{
data += d;
}
- (void)connectionDidFinishLoading:(CPURLConnection)c
{
connection = undefined;
if ([delegate respondsToSelector:@selector(serviceDelegate:gotJSONObject:)]) {
var obj;
try {
obj = JSON.parse(data);
}
catch (e) {
}
if (obj) {
[delegate serviceDelegate:self gotJSONObject:obj];
}
else {
if ([delegate respondsToSelector:@selector(serviceDelegate:failedWithError:)]) {
[delegate serviceDelegate:self failedWithError:"Unexpected response from server"];
}
}
}
data = "";
if (queuedConnection) {
connection = queuedConnection;
[self start];
queuedConnection = undefined;
}
}
- (void)start
{
if ([delegate respondsToSelector:@selector(serviceDelegateDidBeginConnection:)]) {
[delegate serviceDelegateDidBeginConnection:self];
}
[connection start];
}
//-(void)get:(CPString)path;
-(void)post:(CPString)path withData:(id)obj
{
var url = [CPURL URLWithString:endpoint + path];
var request = [CPURLRequest requestWithURL:url];
[request setHTTPBody:JSON.stringify(obj)];
[request setHTTPMethod:"POST"];
var conn = [CPURLConnection connectionWithRequest:request delegate:self];
// If an active connection, then queueConnection for later
if (!connection) {
connection = conn;
[self start];
}
else {
[connection cancel];
queuedConnection = conn;
}
}
// - (void)serviceDelegate:(id)svc gotJSONObject:(id)obj
// - (void)serviceDelegate:(id)svc failedWithError:(id)error;
// - (void)serviceDelegateDidBeginConnection:(id)svc
-(void)setDelegate:(id)del
{
delegate = del;
}
@end