Skip to content

Instantly share code, notes, and snippets.

@willrichman
Created November 18, 2014 18:23
Show Gist options
  • Save willrichman/0c12a93ad4bd1c609f0e to your computer and use it in GitHub Desktop.
Save willrichman/0c12a93ad4bd1c609f0e to your computer and use it in GitHub Desktop.
POST and JSON into data
- (void)postDot: (Dot*)dot completionHandler: (void (^)(NSString *error, bool success))completionHandler {
NSString *fullURLString = [NSString stringWithFormat: @"%@dots/", self.url];
NSURL *fullURL = [NSURL URLWithString:fullURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fullURL];
request.HTTPMethod = @"POST";
NSData *dotJSONData = [dot parseDotIntoJSON];
NSUInteger length = dotJSONData.length;
[request setValue:[NSString stringWithFormat:@"%li", length] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
request.HTTPBody = dotJSONData;
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error != nil) {
NSLog(@"%@", error.localizedDescription);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = httpResponse.statusCode;
if (statusCode >= 200 && statusCode <= 299) {
NSError *postError;
NSDictionary *successJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error: &postError];
NSTimeInterval timestamp = [successJSON[@"time"] doubleValue] / 1000;
dot.timestamp = [NSDate dateWithTimeIntervalSince1970:timestamp];
dot.identifier = successJSON[@"dot_id"];
NSLog(@"Time: %@ Id: %@", dot.timestamp.description, dot.identifier);
completionHandler(nil, YES);
} else {
NSLog(@"%@", httpResponse.description);
}
}
}
}];
[dataTask resume];
}
- (NSData *)parseDotIntoJSON {
NSMutableDictionary *dotJSON = [[NSMutableDictionary alloc] init];
[dotJSON setObject:[NSNumber numberWithDouble:self.location.latitude] forKey:@"latitude"];
[dotJSON setObject:[NSNumber numberWithDouble:self.location.longitude] forKey:@"longitude"];
[dotJSON setObject:self.color forKey:@"color"];
[dotJSON setObject:self.title forKey:@"title"];
[dotJSON setObject:self.body forKey:@"body"];
[dotJSON setObject:self.username forKey:@"username_id"];
NSError *error;
NSData *dataToReturn = [NSJSONSerialization dataWithJSONObject:dotJSON options:0 error: &error];
return dataToReturn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment