使用 twitterkit 将图片发布到 Twitter

Posting image to twitter using twitterkit

我正在尝试 post 使用带有自定义 UI 的 Twitter 新 TwitterKit 制作图像和推文。他们提供的唯一文档是如何用他们的观点来做。

所以我可以弄清楚如何在没有图像的情况下做到这一点

NSMutableDictionary *message = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[params objectForKey:@"description"],@"status",@"true",@"wrap_links", nil];

NSURLRequest* request = [twAPIClient URLRequestWithMethod:@"POST" URL:@"https://api.twitter.com/1.1/statuses/update.json" parameters:message error:nil];

[twAPIClient sendTwitterRequest:request completion:^(NSURLResponse* response, NSData* data, NSError* connectionError){



}];

但是他们的 URLRequestWithMethod 方法是不可变的。我将如何向其中添加图像。您曾经使用

的 SLRequest 来完成它
[postRequest addMultipartData:UIImageJPEGRepresentation(image, 0.5) withName:@"media" type:@"image/jpeg" filename:@"image.png"];

我想通了。

首先,您需要post 将图像发送到 Twitter。

NSString *media = @"https://upload.twitter.com/1.1/media/upload.json";

NSData *imageData = UIImageJPEGRepresentation(image, 0.9);

NSString *imageString = [corgiData base64EncodedStringWithOptions:0];               

NSURLRequest *request = [client URLRequestWithMethod:@"POST" URL:media parameters:@{@"media":imageString} error:&requestError];

[[[Twitter sharedInstance] APIClient] sendTwitterRequest:request completion:^(NSURLResponse *urlResponse, NSData *data, NSError *connectionError) {


}];

然后在响应对象中使用 media_id_string 并将其添加到我问题中代码的参数中。

所以

NSMutableDictionary *message = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[params objectForKey:@"description"],@"status",@"true",@"wrap_links",mediaIDString, @"media_ids", nil];

NSURLRequest* request = [twAPIClient URLRequestWithMethod:@"POST" URL:@"https://api.twitter.com/1.1/statuses/update.json" parameters:message error:nil];

[twAPIClient sendTwitterRequest:request completion:^(NSURLResponse* response, NSData* data, NSError* connectionError){

 NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&parsingError];

}];

注意第一个请求的响应中的 media_ids 对象

NSMutableDictionary *message = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[params objectForKey:@"description"],@"status",@"true",@"wrap_links",[responseDict objectForKey:@"media_id_string"], @"media_ids", nil];

所以你可以把它放在完成块中,它会 post 图片和推文。

Swift

func post (tweetString: String, tweetImage: NSData) {

    let uploadUrl = "https://upload.twitter.com/1.1/media/upload.json"
    let updateUrl = "https://api.twitter.com/1.1/statuses/update.json"
    let imageString = tweetImage.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
    let request = Twitter.sharedInstance().APIClient.URLRequestWithMethod("POST",
        URL: uploadUrl, parameters: ["media": imageString], error: nil)
    Twitter.sharedInstance().APIClient.sendTwitterRequest(request, completion: { (urlResponse, data, connectionError) -> Void in

        if let mediaDict = self.nsdataToJSON(data!) {
            let validTweetString = TweetValidator().validTween(tweetString)
            let message = ["status": validTweetString, "media_ids": mediaDict["media_id_string"]]
            let request = Twitter.sharedInstance().APIClient.URLRequestWithMethod("POST",
                URL: updateUrl, parameters: message, error:nil)

                Twitter.sharedInstance().APIClient.sendTwitterRequest(request, completion: { (response, data, connectionError) -> Void in
            })
        }
    })
}

func nsdataToJSON (data: NSData) -> AnyObject? {
    do {
        return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil
}

截至 2016 年 4 月左右,Fabric 的 TwitterKit 2.0(或更新版本)公开了一种新方法 uploadMedia 来涵盖媒体上传部分。这是一些对我有用的 objc 代码。

(earlier)
self.userID = [[Twitter sharedInstance] sessionStore].session.userID;

- (void)tweetImage:(UIImage*)image {
        NSAssert([NSThread currentThread].isMainThread && self.userID, @"Twitterkit needs main thread, with self.userID set");
        if (!self.userID)
            return;
        NSString *tweetStr = @"Look at me! I'm tweeting! #hashtag";

        TWTRAPIClient *twitterClient = [[TWTRAPIClient alloc] initWithUserID:self.userID];
        NSData *imgData = UIImageJPEGRepresentation(image, 0.6f);
        if (!imgData) {
            NSAssert(false, @"ERROR: could not make nsdata out of image");
            return;
        }
        [twitterClient uploadMedia:imgData contentType:@"image/jpeg" completion:^(NSString * _Nullable mediaID, NSError * _Nullable error) {
            if (error) {
                NSAssert(false, @"ERROR: error uploading collage to twitter");
                return;
            }

            NSError *urlerror = nil;
            NSURLRequest *request = [twitterClient URLRequestWithMethod:@"POST" URL:@"https://api.twitter.com/1.1/statuses/update.json" parameters:@{ @"status":tweetStr, @"media_ids":mediaID } error:&urlerror];
            if (urlerror) {
                NSAssert(false, @"ERROR creating twitter URL request: %@", urlerror);
                return;
            }
            [twitterClient sendTwitterRequest:request completion:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                if (!connectionError && ((NSHTTPURLResponse*)response).statusCode != 200) {
                    DDLogInfo(@"TwitterHelper tweetImage: non-200 response: %d. Data:\n%@", (int)((NSHTTPURLResponse*)response).statusCode, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                }
            }];
        }];
    }

Swift 4 最新

1) 检查登录是否完成

let store = TWTRTwitter.sharedInstance().sessionStore
    if let store = store.session() {
        print("signed in as \(String(describing: store.authToken))");
        print("signed in as \(String(describing: store.authTokenSecret))");
        let postImage = UIImage(named: "testImage")
        let imageData = UIImagePNGRepresentation(postImage!) as Data?

        self.post(tweetString: "Test post image", tweetImage: (imageData! as NSData) as Data, withUserID: store.userID)
    }
    else {
        TWTRTwitter.sharedInstance().logIn(completion: { (session, error) in
            if (session != nil) {
                print("login first time in twitter as \(String(describing: session?.userName))");
            } else {
                print("error: \(String(describing: error?.localizedDescription))");
            }
        })
    }

2) 上传带文字的图片

func post(tweetString: String, tweetImage: Data ,withUserID :String) {

    let uploadUrl = "https://upload.twitter.com/1.1/media/upload.json"
    let updateUrl = "https://api.twitter.com/1.1/statuses/update.json"
    let imageString = tweetImage.base64EncodedString(options: NSData.Base64EncodingOptions())

    let client = TWTRAPIClient.init(userID: withUserID)

    let requestUploadUrl = client.urlRequest(withMethod: "POST", urlString: uploadUrl, parameters: ["media": imageString], error: nil)

    client.sendTwitterRequest(requestUploadUrl) { (urlResponse, data, connectionError) -> Void in
        if connectionError == nil {
            if let mediaDict = self.nsDataToJson(data: (data! as NSData) as Data) as? [String : Any] {
                let media_id = mediaDict["media_id_string"] as! String
                let message = ["status": tweetString, "media_ids": media_id]

                let requestUpdateUrl = client.urlRequest(withMethod: "POST", urlString: updateUrl, parameters: message, error: nil)

                client.sendTwitterRequest(requestUpdateUrl, completion: { (urlResponse, data, connectionError) -> Void in
                    if connectionError == nil {
                        if let _ = self.nsDataToJson(data: (data! as NSData) as Data) as? [String : Any] {
                            print("Upload suceess to Twitter")
                        }
                    }
                })
            }
        }
    }
}

func nsDataToJson (data: Data) -> AnyObject? {
    do {
        return try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as AnyObject
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil
}

注意:安装 pod 文件 pod 'TwitterKit'. 您需要在 appdelegate 和 URL 方案中设置与登录相关的其他小事情(以上代码是与登录和 post 带文字的图像有关)

导入 TwitterKit