2016-04-20 53 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登錄時也可以發送直接消息。也許直接消息權限只需要閱讀或刪除直接消息,但不發送,但然後我回到我原來的問題...

相關問題