首页 > 解决方案 > Twitter - 关注特定用户

问题描述

我正在开发 iOS 应用程序,用户可以从 twitter 登录并关注某些用户。但关注不起作用。

- (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];
}

标签: iosobjective-ctwitterkit

解决方案


您的请求中似乎没有任何身份验证信息。

如果您查看 twitter 文档,它会为您提供 curl 示例

--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' 

您缺少的重要信息在这里 --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"'

您可以通过像这样添加每个标题字段来附加该信息

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


推荐阅读