Reputation: 211
Got a comment to make the main question a separate ticket and separate each question.
I am trying to write code for an SDK. I need to make API calls.
I am using AFNetworking 2.0 to send a POST request to the server:
NSDictionary * params = [self formDictionaryFromCard: card];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString: [self apiUrl] parameters: params];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"Firefox" forHTTPHeaderField:@"User-Agent"];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
successBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
errorBlock(error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
Is this the correct way to use AFNetworking to make API calls for an SDK? How do I provide support for https?
Upvotes: 1
Views: 3449
Reputation: 66224
Is this the correct way to use AFNetworking to make API calls for an SDK?
Your code will work as-is. There are a few suggestions I'd make to change it.
Although the sample code on CocoaDocs shows mainQueue
being used, consider if you want to use a different NSOperationQueue besides mainQueue
. Here are a few possible reasons:
mainQueue
for anything else, and you don't want the priority of those operations to be compared to the priority of your network operations when the system looks at which operation to start nextYou could use AFNetworking's built-in operation queue (on AFHTTPRequestOperationManager):
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.operationQueue addOperation:op];
You could also use one of your own.
You may want to check for the presence of blocks before calling them to void crashes:
if (successBlock) {
successBlock(responseObject);
}
If all or most of your operations will require these customizations to the header, it's probably easier to subclass AFHTTPRequestOperationManager, and override HTTPRequestOperationWithRequest: success: failure:
to add your headers there. Then you can use AFHTTPRequestOperationManager's convenience methods (the ones that begin with POST
and GET
).
Take a look at the documentation for AFHTTPRequestOperationManager.
How do I provide support for https?
For most uses, simply include https
in your URL (in your case, in [self apiUrl]
). For specific uses, such as to allow invalid certs, or to only accept specific ones, you will need to look into the AFSecurityPolicy class.
Upvotes: 3