如何使用OAuth Swift为Tumblr生成签名的POST请求

时间:2015-12-04 00:14:07

标签: ios oauth tumblr nsurlsession nsurlrequest

我正在尝试启动并运行示例Tumblr客户端。我正在使用OAuth Swift库来执行我的OAuth。

现在我的项目有一个按钮。此按钮检查OAuth是否已获得授权。如果是,则将其设置为将一些硬编码数据发布到我设置的测试Tumblr帐户。

我在控制台上收到此输出:

Top of authorizeWithCallbackURL OAuth successfully authorized Request error Server Response: {"meta":{"status":401,"msg":"Not Authorized"},"response":[]}

我的令牌似乎已被接受并且生成了OAuth令牌,但由于某种原因,一旦我获得授权,它就不会包含在我尝试呼叫的POST请求中。

这是我的代码,带有相应的修订:

import UIKit
import OAuthSwift

class ViewController: UIViewController {

    var session:NSURLSession!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func postToTumblr(sender: AnyObject) {
        let oauthSwift = OAuth1Swift(
            consumerKey: "***",
            consumerSecret: "***",
            requestTokenUrl: "https://www.tumblr.com/oauth/request_token",
            authorizeUrl: "https://www.tumblr.com/oauth/authorize",
            accessTokenUrl: "https://www.tumblr.com/oauth/access_token"
        )


        oauthSwift.authorizeWithCallbackURL(NSURL(string: "tumblrsampleapp://oauth-callback")!,
            success: { credential, response in
                // post to Tumblr
                print("OAuth successfully authorized")

                // Configure NSURLSession
                let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
                config.HTTPAdditionalHeaders = ["Authorization":credential]
                self.session = NSURLSession(configuration: config)

                // Post hardcoded data to Tumblr
                let request = self.request("consumerSecretKey&\(credential.oauth_token_secret)")
                let uploadTask = self.session.dataTaskWithRequest(request!) { (responseData, response, error) in

                    // Check on some response headers (if it's HTTP)
                    if let httpResponse = response as? NSHTTPURLResponse {
                        switch httpResponse.statusCode {
                        case 200..<300:
                            print("Success")
                        case 400..<500:
                            print("Request error")
                        case 500..<600:
                            print("Server error")
                        case let otherCode:
                            print("Other code: \(otherCode)")
                        }
                    }

                    // Do something with the response data
                    if let responseData = responseData,
                    responseString = String(data: responseData, encoding: NSUTF8StringEncoding) {
                            print("Server Response:")
                            print(responseString)
                    }

                    // Do something with the error
                    if let error = error {
                        print(error.localizedDescription)
                    }
                }

                uploadTask.resume()

            }, failure: {(error:NSError!) -> Void in
                self.presentAlert("Error", message: error!.localizedDescription)
        })
    }

    func request(credential:String) -> NSURLRequest? {
        guard let url = NSURL(string: "https://api.tumblr.com/v2/blog/{hostname}/post") else {return nil}
        let request = NSMutableURLRequest(URL: url)
        let requestData = self.buildRequestData()

        request.HTTPMethod = "POST"
        request.HTTPBody = requestData
        let postDataLengthString = String(format:"%d", requestData.length)
        let credentialString = String(format:"%d", credential)
        request.setValue(postDataLengthString, forHTTPHeaderField:"Content-Length")
        request.setValue(credentialString, forHTTPHeaderField: "Authorization")
        return request
    }

    func buildRequestData() -> NSData {
        // Getting these parameters from this site:
        // https://www.tumblr.com/docs/en/api/v2#posting
        // It looks like there are a bunch of optional paramters
        let requestDictionary = [
            ["type":"text"],
            ["title": "Hello, World!"],
            ["body": "Hello world. This is my first post."]
        ]

        let data = try? NSJSONSerialization.dataWithJSONObject(requestDictionary, options: NSJSONWritingOptions())

        return data!
    }


    func presentAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }

}

我认为问题涉及request函数没有正确生成标题。我没有看到Tumblr文档中的任何内容说我需要在请求中包含授权令牌,所以我假设他们假设我应该知道这一点。

任何有关我所做错事的见解都将不胜感激。谢谢!

0 个答案:

没有答案