Wanted: Up-to-date example for JSON/POST with basic auth using AFNetworking-2
UPDATE: The JSON portion of the following was found to work for PUT/POST, but NOT for GET/HEAD/DELETE
After some wrangling, and help outside SO, I got something working, which I wanted to leave as a memento. In the end, I was really very impressed with AFNetworking-2. It was so simple, I kept trying to make it harder than it should have been. Given a jsonDict
method that returns the json packet to send, I created the following:
- (void) submitAuthenticatedRest_PUT{ // it all starts with a manager AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // in my case, I'm in prototype mode, I own the network being used currently, // so I can use a self generated cert key, and the following line allows me to use that manager.securityPolicy.allowInvalidCertificates = YES; // Make sure we a JSON serialization policy, not sure what the default is manager.requestSerializer = [AFJSONRequestSerializer serializer]; // No matter the serializer, they all inherit a battery of header setting APIs // Here we do Basic Auth, never do this outside of HTTPS [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"basic_auth_username" password:@"basic_auth_password"]; // Now we can just PUT it to our target URL (note the https). // This will return immediately, when the transaction has finished, // one of either the success or failure blocks will fire [manager PUT: @"https://101.202.303.404:5555/rest/path" parameters: [self jsonDict] success:^(AFHTTPRequestOperation *operation, id responseObject){ NSLog(@"Submit response data: %@", responseObject);} // success callback block failure:^(AFHTTPRequestOperation *operation, NSError *error){ NSLog(@"Error: %@", error);} // failure callback block ];}
3 setup statements, followed by 2 message sends, it really is that easy.
EDIT/ADDED: Here's an example @jsonDict implementation:
- (NSMutableDictionary*) jsonDict{ NSMutableDictionary *result = [[NSMutableDictionary alloc] init]; result[@"serial_id"] = self.serialID; result[@"latitude"] = [NSNumber numberWithDouble: self.location.latitude]; result[@"longitude"] = [NSNumber numberWithDouble: self.location.longitude]; result[@"name"] = self.name; if ([self hasPhoto]) { result[@"photo-jpeg"] = [UIImageJPEGRepresentation(self.photo, 0.5) base64EncodedStringWithOptions: NSDataBase64Encoding76CharacterLineLength];}return result;
}
It should just return a dictionary with string keys, and simple objects as values (NSNumber, NSString, NSArray (I think), etc). The JSON encoder does the rest for you.