22
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【iOS】TwitterKitで画像投稿

Posted at

FabricのTwitter KitのREST APIを使っての画像投稿の記事が見当たらなかったのでc⌒っ゚д゚)っφ メモメモ...

ドキュメントはこちら。情報少なっ!

まずは各API用のNSURLRequestを返すclass作成
「statuses/update」と「media/upload」の2つのAPIを使います。

TwitterAPI.swift

import TwitterKit

class TwitterAPI: NSObject {
    
    /// メディアアップロード用URLRequest
    func uploadMediaAPIRequest(imageData: NSData) -> NSURLRequest? {
        
        let media = imageData.base64EncodedStringWithOptions(nil)
        
        let params = [
            "media" : media
        ]
        
        let apiPath = "https://upload.twitter.com/1.1/media/upload.json"
        
        return Twitter.sharedInstance().APIClient.URLRequestWithMethod("POST", URL: apiPath, parameters: params, error: nil)
    }
    
    /// 投稿用URLRequest
    func statusUpdateAPIRequest(status statusOrNil: String?, mediaIDString: String) -> NSURLRequest? {
        
        let getCommentString = {(commentOrNil: String?) -> String in
            let limitCount = 140
            if let comment = commentOrNil {
                if comment.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > limitCount {
                    let index: String.Index = advance(comment.startIndex, limitCount)
                    return comment.substringToIndex(index)
                }
                return comment
            }
            return ""
        }
        
        let params = [
            "status" : getCommentString(statusOrNil),
            "media_ids" : mediaIDString
        ]
        
        let apiPath = "https://api.twitter.com/1.1/statuses/update.json"
        
        return Twitter.sharedInstance().APIClient.URLRequestWithMethod("POST", URL: apiPath, parameters: params, error: nil)
    }
    
}

次に実行部分


let imageData = UIImageJPEGRepresentation(image, 0.9)!
        
let twitterAPI = TwitterAPI()

Twitter.sharedInstance().APIClient.sendTwitterRequest(twitterAPI.uploadMediaAPIRequest(imageData)!, completion: { (responce: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            
	if error != nil {
		// Errorハンドリング
    	return
    }
            
	let mediaId = {(data: NSData) -> String! in
		if let jsonObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as? [String : AnyObject] {
			return jsonObject["media_id_string"] as? String
		}
		return nil
	}
            
	Twitter.sharedInstance().APIClient.sendTwitterRequest(twitterAPI.statusUpdateAPIRequest(status: commentOrNil, mediaIDString: mediaId(data))!, completion: { (updateResponce: NSURLResponse!, updateData: NSData!, updateError: NSError!) -> Void in
                
		if updateError != nil {
			// Errorハンドリング
       		return
    	}
                
       	// 送信完了
	})
})

「media/upload」で画像を上げてから、返って来る「media_id_string」をくっつけて「statuses/update」でツイートするという流れ。

さすが純正。お手軽すぎるぜ!
(Base64 Encodeしてパラメータにぶっ込むだけ・・の箇所で半日悩んだんですけどね!)

22
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?