使用 Swift 访问 Twitter [英] Access Twitter using Swift

查看:69
本文介绍了使用 Swift 访问 Twitter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Swifter 库在我的 Swift iOS 8 应用程序中访问 Twitter:https://github.com/mattdonnelly/Swifter.问题是我从 Twitter 收到 401 Not Authorized 错误.我仔细检查了任何可能的原因:

I'm using the Swifter library to access Twitter in my Swift iOS 8 app: https://github.com/mattdonnelly/Swifter. The problem is that I'm getting a 401 Not Authorized error from Twitter. I double checked any possible reasons for this:

  1. 消费者密钥/密码错误
  2. 确保不要使用 API v1(使用 1.1)

这两个问题都解决了(根据 Twitter 文档),我仍然面临这个问题.我认为这与我的身份验证方式有关.我正在尝试在设备上不使用 ACAccount 的情况下访问公共供稿.

With both these problems fixed (according to the Twitter docs), I'm still faced with this issue. I'm thinking it has something to do with how I authenticate. I'm trying to access a public feed without using ACAccount on the device.

这是我的代码:

// MARK: Twitter
    var swifter: Swifter

    required init(coder aDecoder: NSCoder) {
        self.swifter = Swifter(consumerKey: "KEY", consumerSecret: "SECRET")
        super.init(coder: aDecoder)
    }

    func getTwitterTimeline() {
        let failureHandler: ((NSError) -> Void) = {
            error in
            self.alertWithTitle("Error", message: error.localizedDescription)
        }

        self.swifter.getStatusesUserTimelineWithUserID("erhsannounce", count: 20, sinceID: nil, maxID: nil, trimUser: true, contributorDetails: false, includeEntities: true, success: {
            (statuses: [JSONValue]?) in

            if statuses != nil {
                self.tweets = statuses!
            }

        }, failure: failureHandler)
    }

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

更新:我一直在开发应用程序,试图实现仅使用应用程序(而不是基于用户的)身份验证和访问令牌来读取公共时间线的功能.

UPDATE: I've been working on the app, trying to achieve the functionality of using App only (not user based) auth and access token to read a public timeline.

我更新了代码以使用访问令牌和仅应用程序身份验证.不过还是不行.

I updated the code to use an access token and app only auth. Still not working though.

required init(coder aDecoder: NSCoder) {
        let accessToken = SwifterCredential.OAuthAccessToken(key: "KEY", secret: "SECRET")
        let credential = SwifterCredential(accessToken: accessToken)

        self.swifter = Swifter(consumerKey: "cKEY", consumerSecret: "cSECRET", appOnly: true)
        swifter.client.credential = credential
        super.init(coder: aDecoder)
    }

推荐答案

更新 02-03-2015

您需要使用仅应用身份验证而不是传入 OAuth 令牌来向服务器进行身份验证.

Update 02-03-2015

You need to authenticate with the server using App Only Authentication rather than passing in an OAuth Token.

除此之外,您在传递用户的屏幕名称时也没有正确使用 userId 请求状态.需要通过username获取user id,然后请求status'.

As well as this, you are also not requesting status' with userId correctly as you are passing in the user's screen name. You need to obtain the user id with the username and then request for status'.

完整的工作代码如下:

required init(coder aDecoder: NSCoder) {
    self.swifter = Swifter(consumerKey: "cKEY", consumerSecret: "cSECRET", appOnly: true)
    super.init(coder: aDecoder)

    self.swifter.authorizeAppOnlyWithSuccess({ (accessToken, response) -> Void in
        self.twitterIsAuthenticated = true
    }, failure: { (error) -> Void in
        println("Error Authenticating: \(error.localizedDescription)")
    })
}

@IBAction func getUserButtonPressed(sender: UIButton?) {
    if (self.twitterIsAuthenticated) {
        self.getTwitterUserWithName("erhsannounce")
    } else {
        // Authenticate twitter again.
    }
}

func getTwitterUserWithName(userName: String) {
    self.swifter.getUsersShowWithScreenName(userName, includeEntities: true, success: { (user) -> Void in
        if let userDict = user {
            if let userId = userDict["id_str"] {
                self.getTwitterStatusWithUserId(userId.string!)
            }
        }
        }, failure: failureHandler)
}

func getTwitterStatusWithUserId(idString: String) {
    let failureHandler: ((error: NSError) -> Void) = {
        error in
        println("Error: \(error.localizedDescription)")
    }

    self.swifter.getStatusesUserTimelineWithUserID(idString, count: 20, sinceID: nil, maxID: nil, trimUser: true, contributorDetails: false, includeEntities: true, success: {
        (statuses: [JSONValue]?) in

        if statuses != nil {
            self.tweets = statuses
        }

        }, failure: failureHandler)
}

<小时>

看起来好像您没有在服务器上进行身份验证.


It looks as though you are not Authenticating with the server.

从您的代码中,我可以看到您正在使用 OAuth 身份验证初始化,但未能调用身份验证函数.

From your code I can see you are using OAuth authentication initialisation but are failing to call the authenticate function.

swifter.authorizeWithCallbackURL(callbackURL, success: {
    (accessToken: SwifterCredential.OAuthAccessToken?, response: NSURLResponse) in

    // Handle success

    },
    failure: {
        (error: NSError) in

        // Handle Failure

    })

添加此内容,然后调用您的 getTwitterTimeline().

Add this in and then call your getTwitterTimeline() afterwards.

希望能帮到你

这篇关于使用 Swift 访问 Twitter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆