Twitter - Follow to certain user

47 Views Asked by At

I am developing the iOS app where user can login from twitter and follow certain users.But following doesn't work.

- (void)executeFollowRequestWithComplition:(nonnull SuccessResultBlock)complition {
    NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

    NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/friendships/create.json"];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

    NSString *postParams = [NSString stringWithFormat:@"screen_name=%@&follow=true", twitterName];

    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[postParams dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
         ANSPerformBlock(complition, (error == nil), error)
    }];

    [dataTask resume];
}
1

There are 1 best solutions below

0
Ben Avery On

You don't appear to have any authentication information in your request.

If you look at the twitter documentation it gives you a curl example

--url 'https://api.twitter.com/1.1/friendships/create.json?user_id=USER_ID_TO_FOLLOW&follow=true' 
--header 'authorization: OAuth oauth_consumer_key="YOUR_CONSUMER_KEY", oauth_nonce="AUTO_GENERATED_NONCE", oauth_signature="AUTO_GENERATED_SIGNATURE", oauth_signature_method="HMAC-SHA1", oauth_timestamp="AUTO_GENERATED_TIMESTAMP", oauth_token="USERS_ACCESS_TOKEN", oauth_version="1.0"' 
--header 'content-type: application/json' 

the important information you are missing is here --header 'authorization: OAuth oauth_consumer_key="YOUR_CONSUMER_KEY", oauth_nonce="AUTO_GENERATED_NONCE", oauth_signature="AUTO_GENERATED_SIGNATURE", oauth_signature_method="HMAC-SHA1", oauth_timestamp="AUTO_GENERATED_TIMESTAMP", oauth_token="USERS_ACCESS_TOKEN", oauth_version="1.0"'

You can append that information by adding each header field like so

urlRequest.addValue("oauth_consumer_key", forHTTPHeaderField: "YOUR_CONSUMER_KEY")