Access Twitter using Swift

后端 未结 1 718
Happy的楠姐
Happy的楠姐 2021-01-24 02:16

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

相关标签:
1条回答
  • 2021-01-24 03:07

    Update 02-03-2015

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

    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'.

    The complete working code is below:

    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.

    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
    
        })
    

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

    I hope this helps

    0 讨论(0)
提交回复
热议问题