Tumblr reblog (TMTumblrSDK) return 401 error - ios

I use TMTumblrSDK :
NSDictionary *params = #{
#"id" : 999999999999,
#"reblog_key": #"XXXXXX",
#"comment" : #"test comment",
};
[[TMAPIClient sharedInstance] reblogPost:#"test.tumblr.com"
parameters:params
callback:^(id response, NSError *error) {
...
response:
{
meta = {
msg = "Not Authorized";
status = 401;
};
response = (
);
}
OAuthConsumerKey, OAuthConsumerSecret, OAuthToken, OAuthTokenSecret is set correctly.
Methods "user/follow" "user/like" and "user/unlike" work correctly.
a similar question about android-version: Getting 401 (Not Authorized), when calling Tumblr post reblog api
also unanswered

I solved my problem.
In the "reblogPost" value necessary to transmit blog url logged in user, not the blog url, reblogged we want to do.
For example, if we want to do reblogged post of "test" user, we must not pass "test.tumblr.com". We must pass "loggedUser.tumblr.com".
It can be obtained using the method userInfo.
For example:
NSString* baseHostname;
[[TMAPIClient sharedInstance] userInfo: ^(id result, NSError* error) {
NSString * baseHostname = [result[#"user"][#"blogs"][0][#"url"] // first blog
stringByReplacingOccurrencesOfString:#"http:" withString:#""];
baseHostname = [baseHostname stringByReplacingOccurrencesOfString:#"/" withString:#""];
[[TMAPIClient sharedInstance] reblogPost: baseHostname // #"loggedUser.tumblr.com"
parameters: params
callback: ^(id response, NSError * error) {
...
}];
}];

Related

Load twitter posts from different users

Hi need to load twitter posts from different users.
I know how to load post from single user.
Perform request with search query FROM:<username>.
Do you know the way how to load posts from different users?
I tried something like this FROM:<username1>&&<username2> - but it doesn't work.
Any ideas?
You can make use of TwitterKit framework which is available in cocoapods GitHub - https://github.com/twitter/twitter-kit-ios/wiki/Access-Twitter's-REST-API
Cocoapods - https://cocoapods.org/pods/TwitterKit
Its twitter's own library, so you can always rely on that.
To load multiple tweets you need to use the below code
let client = TWTRAPIClient()
let tweetIDs = ["510908888888487103", "510908133777777104"]
client.loadTweets(withIDs: tweetIDs) { (tweets, error) -> Void in
// handle the response or error
}
If you want to to access other Twitter API endpoints, you can construct a request manually also like below
let client = TWTRAPIClient()
let statusesShowEndpoint = "https://api.twitter.com/1.1/statuses/show.json"
let params = ["id": "20"]
var clientError : NSError?
let request = client.urlRequest(withMethod: "GET", url: statusesShowEndpoint, parameters: params, error: &clientError)
client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
if connectionError != nil {
print("Error: \(connectionError)")
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print("json: \(json)")
} catch let jsonError as NSError {
print("json error: \(jsonError.localizedDescription)")
}
}
Hope this one helps.
I found an approach. I have to use Twitter iOS SDK and TWTRAPIClient for performing the request. https://api.twitter.com/1.1/statuses/user_timeline.json is endpoint for getting tweets of certain user with some username.
NSURLRequest *r = [[TWTRAPIClient new] URLRequestWithMethod:#"GET"
URL:#"https://api.twitter.com/1.1/statuses/user_timeline.json"
parameters:#{#"screen_name":name}
error:nil];
[[TWTRAPIClient new] sendTwitterRequest:r completion:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if(data){
NSArray *tweets = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[TWTRTweet tweetsWithJSONArray:tweets]
}
}];

I am trying to get my friend name and ids with graph api v2.4, but data returns empty:

hi i am trying to fetch Facebook friend list who using my app when i try this function i getting empty data
my sample code
let request: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/friends", parameters: nil, HTTPMethod: "GET")
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
print("Friends are : \(result)")
} else {
print("Error Getting Friends \(error)");
}
}
and my output is
FBSDKLog: starting with Graph API v2.4, GET requests for /me/friends should contain an explicit "fields" parameter
ID is: 964865453559288
2015-12-21 18:25:55.635[12226:218972] fb_id 964865453559288
Friends are : {
data = (
);
}
USE user_id to fetch friends.It is working fine . Try it
-(void)fetchFriendList:(NSString*)userid
{
NSString *string = [NSString stringWithFormat:#"/%#/taggable_friends",userid];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:string
parameters:nil];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
///// your results
}];
}

Uber Authentication failed "HTTP Status 401: Unauthorized, Response: {"error": "invalid_client"}"

i am using this library for Uber Authetication
https://developer.uber.com/v1/auth/
I have done like this
func doOAuthUber(){
let oauthswift = OAuth2Swift(
consumerKey: "fXfXXXXXXXUo9vtKzobXXXXXUDO",
consumerSecret: "e5XXXXXXXq2w63qz9szEx7uXXXXXXo03W",
authorizeUrl: "https://login.uber.com/oauth/authorize",
accessTokenUrl: "https://login.uber.com/oauth/token",
responseType: "code"
)
var originalString = "jamesappv2://oauth/callback"
var encodedCallBackUrl = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
println("encodedCallBackUrl: \(encodedCallBackUrl)")
let state: String = ""
oauthswift.authorizeWithCallbackURL( NSURL(string: encodedCallBackUrl!)!, scope: "request%20history", state: state, success: {
credential, response in
println(credential.oauth_token)
self.personalDriverLoader.stopAnimating()
}, failure: {(error:NSError!) -> Void in
self.personalDriverLoader.stopAnimating()
println(error.localizedDescription)
})
}
but getting this response
HTTP Status 401: Unauthorized, Response: {"error": "invalid_client"}
I have triple checked that my client_id (consumerKey) and secret (consumerSecret) are correct.
What I have done wrong here
Update:1
this is wired I changed responseType: "code" to responseType: "token" and it worked Got My access token. but I am getting an other issue now
now when ever I try to call the request endpoint api
using below code
#IBAction func btnRequestUberdidClicked(sender: AnyObject) {
self.callRequestAPI("https://sandbox-api.uber.com/v1/requests")
}
func callRequestAPI(url:String){
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
let params:[String: AnyObject] = [
"product_id" : selectedUberProductId,
"start_latitude" : start_lat,
"start_longitude" : start_lng,
"end_latitude" : end_lat,
"end_longitude" : end_lng]
appDelegate.oauthswift.client.post(url, parameters: params,
success: { data, response in
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Success")
println(data)
println(response)
}, failure: {(error:NSError!) -> Void in
println("Error")
println(error)
})
}
I am getting this response
Error Domain=NSURLErrorDomain Code=401 "HTTP Status 401: Unauthorized, Response: {"message":"Invalid OAuth 2.0 credentials provided.","code":"unauthorized"}" UserInfo=0x1c563220 {NSLocalizedDescription=HTTP Status 401: Unauthorized, Response: {"message":"Invalid OAuth 2.0 credentials provided.","code":"unauthorized"}, Response-Headers=<CFBasicHash 0x1c578c40 [0x35305710]>{type = immutable dict, count = 7,
entries =>
1 : x-xss-protection = <CFString 0x1ae2fc60 [0x35305710]>{contents = "1; mode=block"}
4 : Server = <CFString 0x1acc24c0 [0x35305710]>{contents = "nginx"}
5 : Content-Type = <CFString 0x1c4d0020 [0x35305710]>{contents = "application/json"}
6 : Content-Length = <CFString 0x1c4b70b0 [0x35305710]>{contents = "75"}
8 : Date = <CFString 0x1c4ed4b0 [0x35305710]>{contents = "Wed, 06 May 2015 12:46:51 GMT"}
10 : Strict-Transport-Security = <CFString 0x1c225cb0 [0x35305710]>{contents = "max-age=31536000; includeSubDomains; preload"}
11 : x-uber-app = <CFString 0x1c49a6b0 [0x35305710]>{contents = "uberex-sandbox"}
}
}
You will have to modify the library where possible and be able to print the auth code returned from Uber. I was facing a similar problem with Uber authentication using objective C and then I realised from my logs that Uber was appending #_ to the authorization code. So when this code was used to fetch the access token, it would fail with (401) unauthorised error simply saying the auth code is invalid, and indeed it was.
See attached image below.
So eventually I had to removed the #_ from the auth code before using it to get the access token.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params1 = #{#"client_secret":UBER_CLIENT_SECRET,
#"client_id":UBER_CLIENT_ID,
#"grant_type":#"authorization_code",
#"redirect_uri":UBER_REDIRECT_URL,
#"code":[app.uberAuthCodeStr stringByReplacingOccurrencesOfString:#"#_" withString:#""]};
//******* THE FIX IS HERE ON THIS LINE ^^^
[manager POST:#"https://login.uber.com/oauth/v2/token" parameters:params1 success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(#"JSON: %#", responseObject);
//
app.uberBearerAccess_token = [responseObject valueForKey:#"access_token"];
app.uberBearerRefresh_token = [responseObject valueForKey:#"refresh_token"];
NSLog(#"Bearer AccessToken = %# ",app.uberBearerAccess_token);
// Save access token to user defaults for later use.
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSNumber *seconds = [responseObject objectForKey:#"expires_in"];
NSDate *expiryDate = [[NSDate date] dateByAddingTimeInterval:seconds.intValue];
[defaults setObject:expiryDate forKey:KEY_UBER_TOKEN_EXPIRE_DATE];
[defaults setObject:app.uberBearerAccess_token forKey: KEY_UBER_TOKEN];
[defaults setObject:app.uberBearerRefresh_token forKey: KEY_UBER_REFRESH_TOKEN];
[defaults setObject:app.uberAuthCodeStr forKey: KEY_UBER_AUTH_CODE];
[defaults synchronize];
loginView.hidden = YES;
[self goUberChat];
//
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#':%#", error,params1);
[ProgressHUD dismiss];
}];
Hope this helps you or anyone with a similar problem.
Try this for call Uber Api
NSString *string=[NSString stringWithFormat:#"https://api.uber.com/v1/products"];
NSURL *url=[NSURL URLWithString:string];
AFHTTPSessionManager *manager=[[AFHTTPSessionManager alloc]initWithBaseURL:url];
NSDictionary *parameters = #{#"server_token":#"Your token",#"latitude":#"latitude",#"longitude":#"longitude",
[manager GET: parameters:parameters progress:nil success:^(NSURLSessionTask *task,id responseObject){
} failure:^(NSURLSessionTask *operation , NSError *error)
}];

iOS: fetch Facebook friends with pagination using 'next'

I am trying to fetch 'taggable_friends' list from Facebook, where there may be more than 1000 taggable friends, so Facebook paginates the results. Here is the method.
-(void)getsFbTaggableFriends:(NSString *)nextCursor dicFBFriends:(NSMutableArray *) dicFriends failure:(void (^) (NSError *error))failureHandler
{
NSString *qry = #"/me/taggable_friends";
NSMutableDictionary *parameters;
if (nextCursor == nil) {
parameters = nil;
}
else {
parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:nextCursor forKey:#"next"];
}
[FBRequestConnection startWithGraphPath:qry
parameters:parameters
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
if (error) {
NSLog(#"%#", [error localizedDescription]);
}else {
/* handle the result */
NSMutableDictionary *mDicResult = [[NSMutableDictionary alloc]initWithDictionary:result];
for (NSDictionary * fbItem in [mDicResult valueForKey:#"data"])
{
[dicFriends addObject:fbItem];
}
// if 'next' value is found, then call recursively
if ([[mDicResult valueForKey:#"paging"] objectForKey:#"next"] != nil) {
NSString *nextCursor = mDicResult[#"paging"][#"next"];
NSLog(#"next:%#", [nextCursor substringFromIndex:27]);
[self getsFbTaggableFriends:nextCursor dicFBFriends:dicFriends failure:^(NSError *error) {
failureHandler(error);
}];
}
}
}];
}
Problem:
I get first 1000 records in the 'result' object and the value of the 'next' key is passed as the "parameters" parameter for the recursive call. However, the second iteration doesn't paginate & keeps returning the same 1000 records.
I also tried using the nextCursor value as the startWithGraphPath parameter for the second call instead. It resulted in a different response object with keys like og_object, share, id instead of data & paging.
Please help to properly obtain the taggable friends page by page, as long as 'next' value is present in the response object. Thank you.
Use the returned next endpoint (Graph path portion, including the cursor) as the new Graph path for the subsequent request, instead putting it as the parameter.
I have come across all the answers. Most of the answers are suggesting either URL based pagination or recursively calling function. We can do this from Facebook SDK itself.
var friendsParams = "taggable_friends"
// Save the after cursor in your data model
if let nextPageCursor = user?.friendsNextPages?.after {
friendsParams += ".limit(10)" + ".after(" + nextPageCursor + ")"
} else {
self.user?.friends.removeAll()
}
let requiredParams = friendsParams + "{id, name, first_name, last_name, picture.width(200).height(200)}"
let params = ["fields": requiredParams]
let _ = FBSDKGraphRequest(graphPath: "me", parameters: params).start { connection, response, error in
if connection?.urlResponse.statusCode == 200 {
print("\(response)")
// Update the UI and next page (after) cursor
} else {
print("Not able to fetch \(error)")
}
}
You can also find the example project here

Getting 401 on PATCH Request sent with AFNetworking/RestKit but 202 sent from Browser

So I have this RESTful API running on top of my Django server by using Tastypie.
So I am doing the following code from javascript, and everything works fine.
var newData = {};
newData["content"] = "This is a new test";
$.ajax({
type: 'patch',
contentType: "application/json; charset=utf-8",
url: "/api/rest/sopsteps/17/",
data: JSON.stringify(newData),
dataType: "json",
success: function(data, status) {
alert("success");
},
error: function(data, status){
alert(data + " STATUS : " + status);
},
});
Now if I do the following using AFNetworking/RestKit I always get a 401 back.
[26/Dec/2012 16:20:20] "PATCH /api/rest/sopsteps/17/ HTTP/1.1" 401 0
NSDictionary* params = [[NSDictionary alloc] initWithObjectsAndKeys: _contentTextView.text, #"content", nil];
NSString *path = [NSString stringWithFormat:#"/api/rest/sopsteps/%#/",((PokaSOPStep *)_step).identifier];
[[objectManager HTTPClient]patchPath:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
{
_step.content = _contentTextView.text;
NSLog(#"%#", operation.responseString);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
if(operation.responseData)
{
id json = [NSJSONSerialization JSONObjectWithData:operation.responseData options:0 error:nil];
if(!json)
{
NSLog(#"An unexpected error occurred. No JSON from Server");
}
else
{
NSLog(#"An unexpected error occurred.");
}
}
else
{
NSLog(#"The Server is currently not responding.");
}
}];
but if I do it from the browser, I get:
[26/Dec/2012 16:54:57] "PATCH /api/rest/sopsteps/17/ HTTP/1.1" 202 0
Any ideas?! Thanks!
401 is the HTTP code for "unauthorized". The reason you're getting different results in the browser and AFNetworking is that you're logged into the former, but not the latter (you can check this by trying this in another browser).
I don't know what kind of authentication scheme you have set up for your server, but you'll need to log into that on iOS before you'll be able to make that request.

Resources