How to make a POST call and send parameters with objective-c in iOS
Solution 1
To post a json data you can try this
-(void)PostJson {
__block NSMutableDictionary *resultsDictionary;
NSDictionary *userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"first title", @"title",@"1",@"blog_id", nil];//if your json structure is something like {"title":"first title","blog_id":"1"}
if ([NSJSONSerialization isValidJSONObject:userDictionary]) {//validate it
NSError* error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error: &error];
NSURL* url = [NSURL URLWithString:@"www.google.com"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:@"POST"];//use POST
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:jsonData];//set data
__block NSError *error1 = [[NSError alloc] init];
//use async way to connect network
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse* response,NSData* data,NSError* error)
{
if ([data length]>0 && error == nil) {
resultsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
NSLog(@"resultsDictionary is %@",resultsDictionary);
} else if ([data length]==0 && error ==nil) {
NSLog(@" download data is null");
} else if( error!=nil) {
NSLog(@" error is %@",error);
}
}];
}
}
Solution 2
I use this code to make URL calls and send data with post
NSURL *url = [NSURL URLWithString:@"http://[YOUR URL]/comment.php?"];
//The URL where you send the POST
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60];
[req setHTTPMethod:@"POST"]; //Set method to POST
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//Set headers for the data, in this case TEXT
//Valor del post
//NSString *UUID = [[NSUUID UUID] UUIDString];
NSString *postData = [NSString stringWithFormat:@"&id=%@&name=%@&comment=%@", self.postID, userName, messageToPost]; //Send the POST Values
NSLog(@"self.postID == %@", self.postID); //Check the POST data
NSString *length = [NSString stringWithFormat:@"%d", [postData length]];
[req setValue:length forHTTPHeaderField:@"Content-Length"]; //Set the POST length
NSLog(@" tamano: %d", postData.length); //Check the length of the POST to send
[req setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]]; //Send the content to the URL
NSHTTPURLResponse* urlResponse = nil; //Response
NSError *err = [[NSError alloc] init]; //Allocate error
NSData *responseData = [NSURLConnection sendSynchronousRequest:req
returningResponse:&urlResponse
error:&err];
//Guardamos los parametros que obtuvimos en la respuesta
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding]; //Save the response as string
NSLog(@"Respueta: %@", responseString); //Check the response
Hope this help you
Solution 3
First off all make a constant in #import "AFAppDotNetAPIClient.m" which you can add by importing AFNetworking Framework and make a constant in .m file
static NSString * const AFAppDotNetAPIBaseURLString = @"http://demo.urmart.in/u-ryd/";
Replace it With your Url.
NSString *urlString = @"trip_add.php";
[[AFAppDotNetAPIClient sharedClient] POST:urlString parameters:tripData constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSString *sucessStr = [NSString stringWithFormat:@"%@",[dict objectForKey:@"msg"]];
NSLog(@"%@",dict);
NSLog(@"%@",sucessStr);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
}];
tripData = // insert your Dictionary Here and Make it Work
Hope for The best.
Solution 4
-(void)postApiCall:(NSMutableDictionary *)dic urlStr:(NSString *)urlStr response:(NSMutableArray *)response{
NSMutableDictionary *completeDictionary = [NSMutableDictionary new];
[completeDictionary setObject:dic forKey:@"[project name]"];
NSLog(@"completeDictionary==> %@",[completeDictionary description]);
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:completeDictionary options:NSJSONWritingPrettyPrinted error:Nil];
NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonDatastr %@",str);
NSURL * serviceUrl = [NSURL URLWithString:urlStr];
NSLog(@"REquest URL >> %@",serviceUrl);
NSLog(@"REquest XML >> %@",str);
NSMutableURLRequest * serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl];
[serviceRequest setValue:@"Application/json" forHTTPHeaderField:@"Content-type"];
[serviceRequest setHTTPMethod:@"POST"];
[serviceRequest setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *serviceResponse;
NSError *serviceError;
NSData *responseData = [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
if (responseData) {
[self parsePostApiData:responseData responseP:response];
}
else{
// AlertViewClass *a = [[AlertViewClass alloc] init];
// [a showMessage:@"Cannot connect to internet." title:@"Skillgrok"];
}
}
-(void)parsePostApiData:(NSData *)response responseP:(NSMutableArray *)responseP{
id jsonObject = Nil;
NSString *charlieSendString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(@"ResponseString %@",charlieSendString);
if (response==nil) {
NSLog(@"No internet connection.");
// AlertViewClass *a = [[AlertViewClass alloc] init];
// [a showMessage:@"Cannot connect to internet." title:@"Skillgrok"];
}
else{
NSError *error = Nil;
jsonObject =[NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(@"Probably An Array");
}
else
{
NSLog(@"Probably A Dictionary");
NSDictionary *jsonDictionary=(NSDictionary *)jsonObject;
NSLog(@"jsonDictionary %@",[jsonDictionary description]);
if (jsonDictionary) {
[responseP addObject:jsonDictionary];
}
}
}
}
skinsfan00atg
Updated on June 05, 2022Comments
-
skinsfan00atg almost 2 years
I'm adding the ability to share an article on LinkedIn in an iOS 7 app using oauth2. I've gotten thru the authentication and have the access token. The documentation seems to be pretty clear about that, but it's odd, to actually post, things get pretty vague and poorly documented. I know I post here: http://api.linkedin.com/v1/people/~/shares appending the token.
iOS being a huge platform and linkedin being very popular, i assumed i was missing something obvious, but a lot of googling has revealed the same old references to old projects. One example uses oauth2 and does get me through authentication but i can't make any api calls. Am i missing a page from linkedin itself? I've read the share api page, but when it comes to the api calls, theres not a single example on using objective-c. i'm not looking to not do anything, but I'm just kinda amazed at the lack of info.
Every example just has the same code using OAMutableRequest, building the dictionary,etc. but they never explain what that is, how to incorporate that library or anything, its just strange. Is this the accepted best practice, the library hasn't been updated in 3 years so it has errors for arc and other things. All the code examples mention the same "consumer" property with no discussion of how or why that's needed. I can't seem to find how you build the post request with the parameters linkedin needs to post something on the site. Is OAMutableRequest the only way? If so, how have people updated it to work? If not, how can you build the request otherwise using NSURLRequest or something simpler. Thanks so much!