繁体   English   中英

如何使用iOS向Twitter朋友发送直接消息

[英]How to send direct message to Twitter friend using iOS

我想直接向Twitter朋友发送消息。 我正在使用以下代码( appdelegate.twitterAccount是来自iOS ACAccountStore的Twitter帐户):

AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSString *idString = @"123456789"; // should be some read user_id
NSString *urlString = @"https://api.twitter.com/1.1/direct_messages/new.json?";
NSURL *postDirectMessageRequestURL = [NSURL URLWithString:urlString];
NSDictionary *parameters = @{@"user_id": idString,
                             @"text": @"some text"};
SLRequest *postDirectMessageRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter 
                                                         requestMethod:SLRequestMethodPOST 
                                                                   URL:postDirectMessageRequestURL 
                                                            parameters:parameters];
postDirectMessageRequest.account = appdelegate.twitterAccount;
[postDirectMessageRequest performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *urlResponse, NSError *error) {
    if (nil != error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"urlResponse: %@", urlResponse);
    }
}];

不幸的是,尽管在iOS中正确设置了Twitter帐户,但出现以下错误:

Error Domain=kCFErrorDomainCFNetwork Code=-1012 "(null)" UserInfo={_kCFURLErrorAuthFailedResponseKey=<CFURLResponse 0x160352490 [0x19ebeb150]>{url = https://api.twitter.com/1.1/direct_messages/new.json?}}}, NSErrorFailingURLKey=https://api.twitter.com/1.1/direct_messages/new.json?}

那么,身份验证出了点问题,但是呢?

发生问题的简单答案(可能是错误的,请参见下文),是通过iOS登录到Twitter的应用没有直接消息权限,如所使用的Twitter帐户的“应用”设置所示:
在此处输入图片说明 对不起,德国人。 它说读和写许可,即没有直接消息许可。

我使用Fabric和Twitter框架解决了这个问题。
我下载了Mac Fabric应用程序 ,可让您轻松安装Twitter框架。 它甚至允许您复制和粘贴所需的基本代码。
我定义了一个Twitter_Helper类,其中包含以下方法:

+(void)twitterInit {
    [Fabric with:@[[Twitter class]]]; // initialize Twitter
}

+(void)loginCompletion:(void(^)(TWTRSession *, NSError *))completionBlock_ {
    [[Twitter sharedInstance] logInWithMethods:TWTRLoginMethodSystemAccounts | TWTRLoginMethodWebBased 
                                    completion:^(TWTRSession *session, NSError *error) {
        if (nil == session) {
            NSLog(@"error: %@", [error localizedDescription]);
        }
        completionBlock_(session, error);
    }];
}

+(TWTRAPIClient *)getTwitterClientForCurrentSession {
    NSString *userID = [Twitter sharedInstance].sessionStore.session.userID;
    TWTRAPIClient *client = [[TWTRAPIClient alloc] initWithUserID:userID];
    return client;
}

+(void)loadFollowersOfUserWithId:(NSString *)userId completion:(void(^)(NSDictionary *, NSError *))completionBlock_ {
    TWTRAPIClient *client = [Twitter_Helper getTwitterClientForCurrentSession];
    NSString *loadFollowersEndpoint = @"https://api.twitter.com/1.1/followers/ids.json";
    NSDictionary *params = @{@"user_id" : userId};
    NSError *clientError;

    NSURLRequest *request = [client URLRequestWithMethod:@"GET" URL:loadFollowersEndpoint parameters:params error:&clientError];

    if (request) {
        [client sendTwitterRequest:request completion:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (data) {
                NSDictionary *followersDictionary = [NSJSONSerialization JSONObjectWithData:data
                                                                                  options:NSJSONReadingMutableContainers
                                                                                    error:nil];
                completionBlock_(followersDictionary, nil);
            }
            else {
                completionBlock_(nil, connectionError);
            }
        }];
    }
    else {
        completionBlock_(nil, clientError);
    }
}

+(void)sendDirectMessage:(NSString *)message toUserWithId:(NSString *)userId completion:(void(^)(NSError *))completionBlock_ {
    TWTRAPIClient *client = [Twitter_Helper getTwitterClientForCurrentSession];
    NSString *sendDirectMessageEndpoint = @"https://api.twitter.com/1.1/direct_messages/new.json";
    NSDictionary *params = @{@"user_id" : userId,
                             @"text"    : message};
    NSError *clientError;

    NSURLRequest *request = [client URLRequestWithMethod:@"POST" URL:sendDirectMessageEndpoint parameters:params error:&clientError];

    if (request) {
        [client sendTwitterRequest:request completion:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            completionBlock_(connectionError);
        }];
    }
    else {
        completionBlock_(clientError);
    }
}

当我想直接发送消息给用户的跟随者(一次只能直接发送消息给追随者),我登录的用户在使用loginCompletion:通过读取用户的跟随IDS loadFollowersOfUserWithId:completion: ,然后发送邮件通过sendDirectMessage:toUserWithId:completion:
这没有任何问题。

我不明白的是:
我首先使用TWTRLoginMethodWebBased登录,因为Twitter文档说:
TWTRLoginMethodSystemAccounts 尝试使用系统帐户登录用户。 此登录方法仅将有限的应用程序权限授予返回的oauth令牌。 如果您想授予更多的应用程序权限,则必须使用TWTRLoginMethodWebBased并正确配置应用程序。
TWTRLoginMethodWebBased 呈现一个允许用户登录的Web视图。此方法将允许开发人员请求更多的应用程序权限。

但是,当我使用TWTRLoginMethodWebBased登录时,我没有任何机会请求直接消息权限。 这是登录屏幕:
在此处输入图片说明

它说我将没有直接消息许可权,并且当我查看应用程序设置时,该许可权实际上仅是读写权限:
在此处输入图片说明 更奇怪的是,当我使用TWTRLoginMethodSystemAccounts登录时,我也可以发送直接消息。 也许只有直接消息许可才需要阅读或删除直接消息,而发送则不需要,但是我又回到了最初的问题……

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM