2016-04-20 139 views
2

我想向Twitter好友发送直接消息。我使用下面的代码(appdelegate.twitterAccount是从iOS Twitter账号ACAccountStore):如何使用iOS向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); 
    } 
}]; 

不幸的是,我得到以下错误,虽然Twitter帐户设置正确iOS中:

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?} 

所以,认证有问题,但是什么?

回答

0

简单的回答(可能是错误的,请参阅下文)出错的原因是,iOS上登录Twitter的应用程序没有直接的消息权限,如使用的Twitter帐户的“应用程序”设置中所示:
enter image description here 对不起,德国人。它表示读写权限,即没有直接的消息权限。

我使用Fabric和Twitter框架解决了这个问题。
我下载了Mac Fabric app,可以让你轻松安装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:时,加载用户的追随者ID为loadFollowersOfUserWithId:completion:,然后通过sendDirectMessage:toUserWithId:completion:发送消息。
这工作没有任何问题。

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

但是,当我使用TWTRLoginMethodWebBased登录时,我没有任何请求直接消息权限的机会。这是登录屏幕:
enter image description here

它说,我不会有直接的信息权限,而当我抬起头的应用程序设置,权限确实读取和只写:
enter image description here 更为奇特是我在使用TWTRLoginMethodSystemAccounts登录时也可以发送直接消息。也许直接消息权限只需要阅读或删除直接消息,但不发送,但然后我回到我原来的问题...

相关问题