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. I know I post here: http://api.linkedin.com/v1/people/~/shares appending the token.
But every example then 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? Thanks so much!
After retrieve your Access Token you can use AFNetworking for a POST request like this example code:
NSString *stringRequest = #"https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=ACCESS_TOKEN&format=json";
//Request parameter on a dictionary (keys in camel case)
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
[[NSDictionary alloc] initWithObjectsAndKeys: #"anyone",#"code",nil], #"visibility",
#"comment to share", #"comment",
[[NSDictionary alloc] initWithObjectsAndKeys:#"description share", #"description",
#"link_url", #"submittedUrl",
#"title share",#"title",
#"image_url",#"submittedImageUrl",nil],
#"content",nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
manager.requestSerializer = requestSerializer;
[manager POST:stringRequest parameters:update success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"result: %#", responseObject);
completionBlock(YES, responseObject, nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogError([error localizedDescription]);
completionBlock(NO, nil, error);
}];
Important: the keys of the dictionary are in camel case according to Linkedin API.
In the case linkedin give bad request (error 400), another way to create the dictionary is:
NSMutableDictionary *update = [[NSMutableDictionary alloc] init];
if(message)
{
//Set visibility
NSDictionary *visibility = [[NSDictionary alloc] initWithObjectsAndKeys:#"anyone", #"code", nil];
[update setObject:visibility forKey:#"visibility"];
//Set comment
[update setObject:message forKey:#"comment"];
//Set content or append imageUrl/postUrl to message to share
NSMutableDictionary *content = [[NSMutableDictionary alloc] init];
if(postUrl)
[content setObject:imageUrl forKey:#"submittedUrl"];
if(imageUrl)
[content setObject:imageUrl forKey:#"submittedImageUrl"];
if(postUrl || imageUrl)
[update setObject:content forKey:#"content"];
}
Andr3a88's answer might work, but I could never get everything figured out with linkedin's side. Luckily, they finally released a full sdk: https://developer.linkedin.com/docs/share-on-linkedin, https://developer.linkedin.com/docs/ios-sdk
Related
My Question might be looks like similar to other questions but really this is not.(according to my knowledge). i can't understand that how to fetch a specific image from any URL Like Facebook does, i can't show you screen shot because i don't have real device. but i can show you Skype's screen shot taken from MAC. any help will be appreciated. thanks.
EDIT:i got favicon using this link but it is very small i want that in bigger size.
finally, i got the answer. this might be helpful to you thats why i post this answer.use this macro#define FACEBOOK_GRAPH #"https://graph.facebook.com/v2.3/oauth/access_token?client_id=USE_YOUR_CLIENT_ID&client_secret=USE_YOUR_CLIENT_SECRET&grant_type=client_credentials"NOTE: you can get "client_id" and "client_secret" by registering your Application on developer.facebook.com now make a call for FACEBOOK_GRAPH Like bellow.
AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
//manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer=[AFJSONResponseSerializer new];
AFHTTPRequestOperation* operation = [manager POST:FACEBOOK_GRAPH parameters:nil
success:^(AFHTTPRequestOperation* op, id responseObject){
//here pass your URL as a string and access Token as a string, access token will found in responseObject
}
failure:^(AFHTTPRequestOperation* op, NSError* error){
NSLog(#"\n\nerror--->%#\n\n",error.localizedDescription);
}];
[operation start];
now the second method to get image from our URL, use our URL and access Token got from above method
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
token = [token stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFJSONResponseSerializer new];
AFHTTPRequestOperation* operation = [manager POST:[NSString stringWithFormat:#"https://graph.facebook.com/v2.3/?id=%#&access_token=%#&scrape=true",url,token] parameters:nil success:^(AFHTTPRequestOperation* op, id responseObject){
NSLog(#"\n\nData Response==\n%#\n",responseObject);
//you will get Image URL in response
}failure:^(AFHTTPRequestOperation* op, NSError* error){
NSLog(#"##error--->\n%#",error.localizedDescription);
}];
[operation start];
I am sending data to the server it is going successful but response coming with %20 at the space in data what I have sent to server here is the code I am using
NSString *str = [NSString stringWithFormat:#"http://www.me911.com/new/miphone3/android_edithealth.php?profile_id=%#&health_condition=%#&health_insurance_provider=%#&primary_physician_name=%#&primary_physician_phone=%#&last_physical=%ld&blood_type=%#&organ_donor=%#",profileId,txthospital.text,textinsurence.text,txtprimary.text,txtphone.text,dateInMillis,questionNo,textorgan.text];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSLog(#"Healthinfo URL: %#",str);
NSMutableURLRequest *dataRqst = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[dataRqst setHTTPMethod:#"POST"];
NSString *stringBoundary = #"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
NSString *headerBoundary = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary];
[dataRqst addValue:headerBoundary forHTTPHeaderField:#"Content-Type"];
NSMutableData *postBody = [NSMutableData data];
[dataRqst setHTTPBody:postBody];
NSHTTPURLResponse *dataresponse =[[NSHTTPURLResponse alloc] init];
NSError* error = [[NSError alloc] init] ;
//synchronous filling of data from HTTP POST response
NSData *responseData = [NSURLConnection sendSynchronousRequest:dataRqst returningResponse:&dataresponse error:&error];
//convert data into string
NSString *responseString = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding];
NSLog(#"responseString %# ",responseString);
if (responseString == NULL)
{
NSDictionary *infoDic = [[NSDictionary alloc] initWithObjectsAndKeys:#"There was a small problem",
#"title",
#"The network doesn't seem to be responding, please try again.",
#"message",
#"OK",
#"cancel",
#"1",
#"tag",nil,
#"delegate", nil];
[CommonFunctions performSelectorOnMainThread:#selector(showAlertWithInfo:) withObject:infoDic waitUntilDone:NO];
}
else
{
NSDictionary *jsonResponse = [responseString JSONValue];
if ([jsonResponse objectForKey:#"error"]){
NSLog(#"response %#",jsonResponse);
}
else{
}
NSMutableArray *dataresponse=[jsonResponse valueForKey:#"success"];
if ([jsonResponse objectForKey:#"success"])
{
NSLog(#"Array response %#",dataresponse);
}
}
And this is web service
:http://anaadit.net/miphone3/android_edithealth.php?profile_id=287&health_condition=palo%20Alto%20Veterans%20Hospital%20&health_insurance_provider=Blue%20Cross&primary_physician_name=Dr.Akki&primary_physician_phone=6504935000&last_physical=-57600&blood_type=7&organ_donor=No
Here I am sending data in textfield in like guru prasad but response getting like this guru%20prasad.
So please correct me where am I going wrong .
thanks in advance
Your code has a number of issues.
In order to create a URL with query params, I recommend to use the utility class NSURLComponents (see Apple documentation: NSURLComponents).
Composing a POST request whose content type is "multipart/formdata" is quite error prone. If you absolutely have to compose such a request I very strongly recommend to use a Network Library, for example AFNetworking.
On the other hand, using a POST request whose Content-Type is application/json is very easy to setup, especially with NSURLSession and friends.
You can find specific solutions for any of the suggested approaches mentioned above on SO, too.
Its seems there is some problem in parsing data, the space are replaced with %20...It seems you are using NSURL Connection for making API Calls.
Use AFNetworking for making API Calls, the response data will automatically come in JSON format and you can initialize Dictionary from same.
Please find below link for AFNetworking:
https://github.com/AFNetworking/AFNetworking
Please use "AFNetworking" and the code will be:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"profile_id": #"287", #"health_condition": #"palo Alto Veterans Hospital", #"health_insurance_provider": #"Blue Cross",
#"primary_physician_name":#"Dr.Akki",
#"primary_physician_phone":#"6504935000",
#"last_physical":#"-57600",
#"blood_type":#"7",
#"organ_donor":#"No"};
[manager POST:#"http://anaadit.net/miphone3/android_edithealth.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Please try the above code. I think this will help you.
I have to send a JSON - with device id and type - to API, and it will give me another JSON with token and few other things.
I'm fairly new to iOS, it has been three weeks and I'm really new to web services. So, I couldn't figure out how to both send and get a JSON.
I'm trying to use AFNetworking at the same time, which is in my opinion the simplest way. So, I thought it might be good to use POST to send a JSON and I achieved with the following code:
NSString *uniqueIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];//DeviceID
NSLog(#"unique idf: %# and type: %#", uniqueIdentifier, [[NSNumber numberWithInt:1] stringValue]);
NSURL *baseURL = [NSURL URLWithString:BaseURLString];
NSDictionary *parameters = #{#"DeviceId" : uniqueIdentifier, #"Type" : [[NSNumber numberWithInt:1] stringValue]};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:BaseURLString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
So, it returns me the device id and type, I know from writing to log. However I stuckted there. On the other hand, it doesn't reach to the success block. I debuged it right now, and also no printing on log screen although there was a command NSLog for it. What might be problem?
It's just confusing to construct a GET there, for me, honestly. So, I would be really appreciated if you can help me to figure out that situation.
Thanks.
Inside your success block do this -
[self performSelector:#selector(makeGetRequest:) withObject:responseObject];
Write the GET functionality in "makeGetRequest" method
-(void)makeGetRequest:(id)sender {
NSLog(#"responseObject - %#",sender);
// Write GET functionality here
}
Learning steeply on this one so I'd say it's 99% my mistake somewhere.
Trying a simple procedure for my first app.
I want to get data from the web service and output something to a label.
I'm a .NET developer so web service has been done and returns JSON data as expected in a browser.
{"GetVenuesForBrandResult":[{"brandID":0,"createdDate":"/Date(-62135596800000+0000)/","venueID":2,"venueName":"HMV Records"}]}
After looking at SO, decided to use AFNetworking, version 2.0, loaded as a pod.
So everything works in terms of getting the data but 2 questions please;
1) the output view in Xcode shows data thus;
GetVenuesForBrandResult=({brandID = 0;createdDate = "/Date(-62135596800000+0000)/";venueID = 2;venueName = "HMV Records";
}
);
Is this just XCode5 formatting for display purposes? And will my data be json in real terms?
2) How do I consume this?
Tried checking for isKindOfClass to be an nsarray or nsdictionary and these if conditions are never met. Which led me to suspect Q1 is the issue.
Your help to an Xcode newbie is appreciated.
as per Paul's excellent hint, the relevant part of my code is here;
the web service link is hard coded for now for test purposes
NSString *urlstring = #"http://hiddenurl/shopBeaconService/Service1.svc/GetVenuesForBra nd/1";
//NSString *str2 = self.email.text;
//NSString *str3 = #"/";
//NSString *str4 = [self.password text];
//NSString *urlstring = [NSString stringWithFormat:#"%#%#%#%#",str1,str2,str3,str4];
NSURL *url = [NSURL URLWithString:urlstring];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,id responseObject)
{
NSLog(#"%#",responseObject);
// NSDictionary *item = [responseObject objectForKey:#""];
// NSString *title = [item objectForKey:#"venueName"];
//NSLog(#"venue= %#",title);
} failure:nil];
[operation start];
The response object when you use the AFJSONResponseSerializer is an NSDictionary. What you are seeing in your log is the output from [responseObject description] - a method that prints a description for logging purposes.
Ray Wenderlich has a good tutorial on AFNetworking
I have an odd problem... I'm doing this ios http/json post using AFNetworking against a rails server and the expected output is something like:
{"success":true,"auth_token":"4D8CyUsyGZdqo6X1TCeq"}
Sometimes it works as expected, but often on the rails side the request is not detected as a "JSON" request so it serves up HTML. Anyone have an idea on this? Is there something I'm doing wrong with regards to setting up the JSON request?
NSDictionary *parameter = #{#"email":#"philswenson#mymail.com", #"password":#"mypassword"};
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://localhost:3000"]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient postPath:#"api/v1/sessions" parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Here is what we got %#", jsonString);
NSDictionary *loginResult = [jsonString objectFromJSONString];
NSNumber* success = [loginResult objectForKey:#"success"];
NSLog(#"success = %#", success);
NSLog(#"yay");
// sample output:
// {"success":true,"auth_token":"4D8CyUsyGZdqo6X1TCeq"}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self handleConnectionError:error];
}];
I know with my service, I need to add application/jsonrequest for accept to my parameters like this:
NSDictionary *parameter = #{#"email":#"philswenson#mymail.com", #"password":#"mypassword", #"accept:application/jsonrequest"};
The AFJSONParameterEncoding only tells it to send the parameters in a JSON file. I need to send a parameter to tell it how to send the data back.
Add:
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
I tried the suggestions - no dice.... the setDefaultHeader actually caused a crash (whatever the iOS term is for access violation)...
The "accept:application/jsonrequest"} didn't see any difference...
I ended up using this code:
NSDictionary *parameter = #{#"email" : #"phil#gmail.com", #"password" : #"mypw", #"format":#"json"};