Post request with AFNetworking
-
11-12-2019 - |
Question
I am newbie in programming, especially in network side. So now I'm creating app to interact with Instagram. In my project I use AFNetworking. I saw their documentation and many examples here. And I don't understand yet how to get POST request to Instagram API. Please could u give me the real code example or something where I can read about how to do this operation? Please help. I tried to make request like this, it gives no errors and no response. It gives nothing :(
(IBAction)doRequest:(id)sender{
NSURL *baseURL = [NSURL URLWithString:@"http://api.instagram.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:@"Accept"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
user_token, @"access_token",
nil];
[httpClient postPath:@"/feed" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
// reponseObject will hold the data returned by the server.
NSLog(@"data: %@", responseObject);
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error retrieving data: %@", error);
}];
NSLog(@"click!!");
}
Solution
few things to care about.
Instagram API returns JSON so you can use AFJSONRequestOperation which will return an already parsed NSDictionary.
The Instagram API says that:
All endpoints are only accessible via https and are located at api.instagram.com.
You should make a change to your baseURL.
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:yourURL];
NSURLRequest *request = [client requestWithMethod:@"POST"
path:@"/your/path"
parameters:yourParamsDictionary];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
// Do something with JSON
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
{
//
}];
// you can either start your operation like this
[operation start];
// or enqueue it in the client default operations queue.
[client enqueueHTTPRequestOperation:operation];