简体   繁体   中英

iOS - Twitter authentication and tweet

Is there any easy way to authenticate and post a tweet to twitter?

I've already found a post method:

- (void)postImage:(UIImage *)image withStatus:(NSString *)status
{
    ACAccountType *twitterType = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    SLRequestHandler requestHandler = ^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
        if (responseData) {
            NSInteger statusCode = urlResponse.statusCode;
            if (statusCode >= 200 && statusCode < 300) {
                NSDictionary *postResponseData =
                [NSJSONSerialization JSONObjectWithData:responseData
                                                options:NSJSONReadingMutableContainers
                                                  error:NULL];
                NSLog(@"[SUCCESS!] Created Tweet with ID: %@", postResponseData[@"id_str"]);
            }
            else {
                NSLog(@"[ERROR] Server responded: status code %d %@", statusCode,
                      [NSHTTPURLResponse localizedStringForStatusCode:statusCode]);
            }
        }
        else {
            NSLog(@"[ERROR] An error occurred while posting: %@", [error localizedDescription]);
        }
    };

    ACAccountStoreRequestAccessCompletionHandler accountStoreHandler =
    ^(BOOL granted, NSError *error) {
        if (granted) {
            NSArray *accounts = [self.accountStore accountsWithAccountType:twitterType];
            NSURL *url = [NSURL URLWithString:@"https://api.twitter.com"
                          @"/1.1/statuses/update_with_media.json"];
//            NSDictionary *params = @{@"status" : status};
            NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                           status, @"status",
                                           nil];
            SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
                                                    requestMethod:SLRequestMethodPOST
                                                              URL:url
                                                       parameters:params];
            NSData *imageData = UIImageJPEGRepresentation(image, 1.f);
            [request addMultipartData:imageData
                             withName:@"media[]"
                                 type:@"image/jpeg"
                             filename:@"image.jpg"];
            [request setAccount:[accounts lastObject]];
            [request performRequestWithHandler:requestHandler];
        }
        else {
            NSLog(@"[ERROR] An error occurred while asking for user authorization: %@",
                  [error localizedDescription]);
        }
    };

    [self.accountStore requestAccessToAccountsWithType:twitterType
                                               options:NULL
                                            completion:accountStoreHandler];
}

But ofc I got an error

:[ERROR] Server responded: status code 401 unauthorized

How can I achieve the authentication??

I've already registrated my app to twitter, and I got both api keys ( normal and secret ).

This is what I use for making a Twitter post. You may need to declare the properties that are used below:

// ------------------------------------------------------------------------------
// Example usage
// ------------------------------------------------------------------------------

NSString *initialText = @"Test";
UIImage *backgroundImage = [UIImage imageNamed:@"background.png"];
NSURL *url = [NSURL URLWithString:@"http://www.google.com/"];

[self beginSocialNetworkPostForType:SLServiceTypeTwitter 
                        initialText:initialText
                          withImage:backgroundImage
                             andURL:url];

// ------------------------------------------------------------------------------
// Method definition
// ------------------------------------------------------------------------------
-(void)beginSocialNetworkPostForType:(NSString *)serviceType
                         initialText:(NSString *)initialText
                           withImage:(UIImage *)postImage
                                 andURL:(NSURL *)postURL
{
    if([SLComposeViewController isAvailableForServiceType:serviceType])
    {
        self.socialNetworkComposeVC = [SLComposeViewController composeViewControllerForServiceType:serviceType];

        if(postImage)
        {
            [self.socialNetworkComposeVC addImage:postImage];
        }

        if(initialText)
        {
            [self.socialNetworkComposeVC setInitialText:initialText];
        }

        if(postURL)
        {
            [self.socialNetworkComposeVC addURL:postURL];
        }

        [self presentViewController:self.socialNetworkComposeVC animated:YES completion:nil];

    }

    [self.socialNetworkComposeVC setCompletionHandler:^(SLComposeViewControllerResult result) {

        NSString *output;

        switch (result)
        {
            case SLComposeViewControllerResultCancelled:
            {
                output = @"Action Cancelled";
                break;
            }
            case SLComposeViewControllerResultDone:
            {
                output = @"Your post was completed successfully";

                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Post Complete" message:output delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                [alert show];

                break;
            }
            default:
                break;
        }
    }];
}

Extra note:

Not sure if this can help you but I also used this reverse authentication library for Twitter by Sean Cook:

https://github.com/seancook/TWReverseAuthExample

It has a method on building a signed request in the TWSignedRequest.m file, perhaps that is of help to you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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