root/apps/iphone/my.tel/trunk/Classes/JsonConnection.m
@
254
| Revision 241, 7.6 kB (checked in by henri, 4 years ago) |
|---|
| Line | |
|---|---|
| 1 | // |
| 2 | // JsonConnection.m |
| 3 | // VIP.tel |
| 4 | // |
| 5 | // Created by Henri Asseily on 11/15/08. |
| 6 | // Copyright 2008 Telnic Ltd.. All rights reserved. |
| 7 | // |
| 8 | |
| 9 | #import "JsonConnection.h" |
| 10 | |
| 11 | @implementation JsonConnection |
| 12 | |
| 13 | @synthesize delegate; |
| 14 | @synthesize jsonUrls; |
| 15 | @synthesize parsedJSON; |
| 16 | @synthesize connectionUrl; |
| 17 | @synthesize theDelegate; |
| 18 | @synthesize actionSel; |
| 19 | @synthesize payload; |
| 20 | @synthesize responsePayload; |
| 21 | @synthesize statusCode; |
| 22 | @synthesize isProcessing; |
| 23 | |
| 24 | extern NSDictionary *jsonUrls; |
| 25 | |
| 26 | #pragma mark ------ Setup Methods |
| 27 | |
| 28 | - (id)init { |
| 29 | self = [super init]; |
| 30 | statusCode = 0; |
| 31 | isProcessing = NO; |
| 32 | [self setPayload:[NSDictionary dictionary]]; |
| 33 | [parsedJSON release]; |
| 34 | [self setConnectionUrl:NULL]; |
| 35 | [self setActionSel:0]; |
| 36 | [self setResponsePayload:[NSMutableString stringWithString:@""]]; |
| 37 | delegate = [[UIApplication sharedApplication] delegate]; |
| 38 | return self; |
| 39 | } |
| 40 | |
| 41 | - (NSURL *)urlFromAction:(NSString *)theAction { |
| 42 | if (!theAction) { |
| 43 | #ifdef JSONDEBUG |
| 44 | NSLog(@"No action defined in %@", NSStringFromSelector(_cmd)); |
| 45 | #endif |
| 46 | return nil; |
| 47 | } |
| 48 | if (![self.jsonUrls valueForKey:theAction]) { |
| 49 | #ifdef JSONDEBUG |
| 50 | NSLog(@"No url defined for action %@", theAction); |
| 51 | #endif |
| 52 | return nil; |
| 53 | } |
| 54 | NSString *jsonUrlString = [self.jsonUrls valueForKey:theAction]; |
| 55 | NSString *apiRootUrlString = [[NSUserDefaults standardUserDefaults] stringForKey:@"apiRootUrl"]; |
| 56 | NSString *fullUrlString = [apiRootUrlString stringByAppendingString:jsonUrlString]; |
| 57 | action = [[NSString stringWithString:theAction] retain]; // For offline mode |
| 58 | return ([NSURL URLWithString:fullUrlString]); |
| 59 | } |
| 60 | |
| 61 | - (void)generateJsonUrls:(NSString *)apiMappings { |
| 62 | self.jsonUrls = [NSDictionary dictionaryWithContentsOfFile: |
| 63 | [[[NSBundle mainBundle] resourcePath] |
| 64 | stringByAppendingPathComponent:apiMappings]]; |
| 65 | return; |
| 66 | } |
| 67 | |
| 68 | - (NSString *)offlineLookupWithAction:(NSString *)theAction { |
| 69 | NSDictionary *results = [NSDictionary dictionaryWithContentsOfFile: |
| 70 | [[[NSBundle mainBundle] resourcePath] |
| 71 | stringByAppendingPathComponent:@"offlineSampleData.plist"]]; |
| 72 | return [results objectForKey:theAction]; |
| 73 | } |
| 74 | |
| 75 | #pragma mark ------ JSON Connection Methods |
| 76 | |
| 77 | - (NSDictionary *)performLookup:(BOOL)async { |
| 78 | #ifdef JSONDEBUG |
| 79 | NSLog(@"URL is: %@", [connectionUrl absoluteString]); |
| 80 | #endif |
| 81 | |
| 82 | // OFFLINE MODE HOOK |
| 83 | |
| 84 | if ([delegate offlineMode]) { |
| 85 | SBJSON *json = [[SBJSON new] autorelease]; |
| 86 | NSError *jsonError; |
| 87 | self.parsedJSON = [json objectWithString:[self offlineLookupWithAction:action] |
| 88 | error:&jsonError]; |
| 89 | if (async) { |
| 90 | [theDelegate performSelector:actionSel withObject:parsedJSON]; |
| 91 | return NULL; |
| 92 | } else { |
| 93 | return parsedJSON; |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | // ONLINE MODE |
| 98 | |
| 99 | NSMutableURLRequest *urlReq = [NSMutableURLRequest requestWithURL:connectionUrl |
| 100 | cachePolicy:NSURLRequestReloadIgnoringLocalCacheData |
| 101 | timeoutInterval:60.0 |
| 102 | ]; |
| 103 | [urlReq setHTTPMethod:@"POST"]; |
| 104 | [urlReq setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; |
| 105 | |
| 106 | NSDictionary *bodyDict = [NSDictionary dictionaryWithObjectsAndKeys: |
| 107 | payload, @"request", |
| 108 | nil |
| 109 | ]; |
| 110 | |
| 111 | NSData *theBody; |
| 112 | theBody = [[(NSObject *)bodyDict JSONRepresentation] dataUsingEncoding:NSUTF8StringEncoding]; |
| 113 | [urlReq setHTTPBody:theBody]; |
| 114 | |
| 115 | #ifdef JSONDEBUG |
| 116 | NSLog(@"Body Representation: %@",[bodyDict JSONRepresentation]); |
| 117 | #endif |
| 118 | |
| 119 | [responsePayload setString:@""]; |
| 120 | |
| 121 | if (async == YES) { |
| 122 | isProcessing = YES; |
| 123 | [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; |
| 124 | NSURLConnection *connection = [[[NSURLConnection alloc] initWithRequest:urlReq delegate:self] autorelease]; |
| 125 | if (connection) { |
| 126 | } else { |
| 127 | #ifdef JSONDEBUG |
| 128 | NSLog(@"Connection error for URL: %@", [connectionUrl description]); |
| 129 | #endif |
| 130 | UIAlertView *alert = [UIAlertView alloc]; |
| 131 | [[alert initWithTitle:@"Error in connection" |
| 132 | message:@"Couldn't create a connection" |
| 133 | delegate:self |
| 134 | cancelButtonTitle:nil |
| 135 | otherButtonTitles:@"OK", nil] autorelease]; |
| 136 | [alert show]; |
| 137 | } |
| 138 | return NULL; |
| 139 | } else { |
| 140 | NSHTTPURLResponse *response = [[[NSHTTPURLResponse alloc] |
| 141 | initWithURL:connectionUrl |
| 142 | MIMEType:@"application/json" |
| 143 | expectedContentLength:1024 |
| 144 | textEncodingName:nil] autorelease]; |
| 145 | NSError *error; |
| 146 | isProcessing = YES; |
| 147 | [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; |
| 148 | NSData *reqResults = [NSURLConnection sendSynchronousRequest:urlReq |
| 149 | returningResponse:&response |
| 150 | error:&error]; |
| 151 | [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; |
| 152 | isProcessing = NO; |
| 153 | if (!reqResults) { |
| 154 | #ifdef JSONDEBUG |
| 155 | NSLog(@"Connection error for URL: %@", [connectionUrl description]); |
| 156 | #endif |
| 157 | UIAlertView *alert = [UIAlertView alloc]; |
| 158 | [[alert initWithTitle:@"Error in connection" |
| 159 | message:[error localizedDescription] |
| 160 | delegate:self |
| 161 | cancelButtonTitle:nil |
| 162 | otherButtonTitles:@"Quit", nil] autorelease]; |
| 163 | [alert show]; |
| 164 | } |
| 165 | NSString *theJSONResult; |
| 166 | theJSONResult = [[[NSString alloc] initWithData:reqResults encoding:NSUTF8StringEncoding] retain]; |
| 167 | |
| 168 | #ifdef JSONDEBUG |
| 169 | NSLog(@"Response payload: %@", theJSONResult); |
| 170 | #endif |
| 171 | SBJSON *json = [[SBJSON new] autorelease]; |
| 172 | NSError *jsonError; |
| 173 | parsedJSON = [json objectWithString:theJSONResult error:&jsonError]; |
| 174 | return parsedJSON; |
| 175 | } |
| 176 | return NULL; |
| 177 | } |
| 178 | |
| 179 | - (void)parsePayload { |
| 180 | SBJSON *json = [[SBJSON new] autorelease]; |
| 181 | NSError *jsonError; |
| 182 | parsedJSON = [json objectWithString:responsePayload error:&jsonError]; |
| 183 | } |
| 184 | |
| 185 | - (void)dealloc { |
| 186 | [action release]; |
| 187 | [super dealloc]; |
| 188 | } |
| 189 | |
| 190 | #pragma mark ------ NSURLConnection delegate methods |
| 191 | |
| 192 | - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { |
| 193 | NSString *newText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; |
| 194 | if (newText != NULL) { |
| 195 | [responsePayload appendString:newText]; |
| 196 | [newText release]; |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | - (void)connectionDidFinishLoading:(NSURLConnection*)connection { |
| 201 | #ifdef JSONDEBUG |
| 202 | NSLog(@"Response payload: %@", responsePayload); |
| 203 | #endif |
| 204 | [self parsePayload]; |
| 205 | [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; |
| 206 | isProcessing = NO; |
| 207 | if (!parsedJSON) { |
| 208 | NSError *theError = [NSError errorWithDomain:@"CustomDomain" |
| 209 | code:404 |
| 210 | userInfo:[NSDictionary dictionaryWithObject:@"Invalid data received" |
| 211 | forKey:NSLocalizedFailureReasonErrorKey]]; |
| 212 | [self connection:connection didFailWithError:theError]; |
| 213 | return; |
| 214 | } |
| 215 | #ifdef JSONDEBUG |
| 216 | if ([[self.parsedJSON valueForKey:@"success"] boolValue] == NO) { |
| 217 | NSLog(@"JSON ERROR REQ: %@\nJSON ERROR ERR: %@,", |
| 218 | self.connectionUrl, |
| 219 | [[(NSArray *)[self.parsedJSON valueForKey:@"actionErrors"] objectAtIndex:0] description] |
| 220 | ); |
| 221 | } |
| 222 | #endif |
| 223 | [theDelegate performSelector:actionSel withObject:parsedJSON]; |
| 224 | } |
| 225 | |
| 226 | - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { |
| 227 | #ifdef JSONDEBUG |
| 228 | NSLog(@"ERROR Response payload: %@", responsePayload); |
| 229 | #endif |
| 230 | [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; |
| 231 | isProcessing = NO; |
| 232 | UIAlertView *alert = [UIAlertView alloc]; |
| 233 | [[alert initWithTitle:@"Error in connection" |
| 234 | message:[error localizedDescription] |
| 235 | delegate:self |
| 236 | cancelButtonTitle:nil |
| 237 | otherButtonTitles:@"OK", nil] autorelease]; |
| 238 | [alert show]; |
| 239 | |
| 240 | [responsePayload appendFormat:@"{\"actionErrors\":[\"%@\"],\"success\":false}", |
| 241 | [error localizedDescription]]; |
| 242 | [self connectionDidFinishLoading:connection]; |
| 243 | } |
| 244 | |
| 245 | + (void)throwJsonErrorAlert:(NSDictionary *)someJson { |
| 246 | UIAlertView *alert = [UIAlertView alloc]; |
| 247 | [[alert initWithTitle:@"Error" |
| 248 | message:[[(NSArray *)[someJson valueForKey:@"actionErrors"] objectAtIndex:0] description] |
| 249 | delegate:self |
| 250 | cancelButtonTitle:nil |
| 251 | otherButtonTitles:@"OK", nil] autorelease]; |
| 252 | [alert show]; |
| 253 | } |
| 254 | |
| 255 | @end |
Note: See TracBrowser
for help on using the browser.








