简体   繁体   中英

How to authenticate API in swift?

I am trying to add the tweets in my app. I have implemented the log in button and trying to access the tweets through search API (Fabric)

https://api.twitter.com/1.1/search/tweets.json?q=Himan_dhawan

It shows me Bad authentication error

And then i make authenticated request by adding the authenticate header in the Header by this code

    let twitter = Twitter.sharedInstance()
    let oauthSigning = TWTROAuthSigning(authConfig:twitter.authConfig, authSession:twitter.session())
    let authHeaders = oauthSigning.OAuthEchoHeadersToVerifyCredentials()
   let request = NSMutableURLRequest(URL: NSURL(string: "https://api.twitter.com/1.1/search/tweets.json?q=Himan_dhawan")!)
    request.allHTTPHeaderFields = authHeaders

But it is still showing me Bad authentication.... I got stuck into how to add tweets in your app... Can any one tell me easiest way to do it ??

let authHeaders = oauthSigning.OAuthEchoHeadersToVerifyCredentials()
let urlHeader: AnyObject? = authHeaders[TWTROAuthEchoAuthorizationHeaderKey]

request.allHTTPHeaderFields = urlHeader

SideNote:

For Twitter API. Very less usage in the wild and has minimal support for swift. For swift, to avoid problems as above, i use swifter. https://github.com/mattdonnelly/Swifter It does all the work for you once u supply your consumer key etc.

The Fabric doc's don't quite give you the full picture about creating the OAuth signing headers when wanting to use your own NSMutableURLRequest.

let authHeaders = oauthSigning.OAuthEchoHeadersToVerifyCredentials()

The return [NSObject : AnyObject]! dictionary gives you the values you need for the request, what it provides for the headers are different to what needs to be sent with the NSMutableURLRequest.

This is how you should be setting the headers for this request:

            let twitter = Twitter.sharedInstance()

            let oauthSigning = TWTROAuthSigning(authConfig:twitter.authConfig, authSession:twitter.session())

            let authHeaders = oauthSigning.OAuthEchoHeadersToVerifyCredentials()

            let mutableUrlWithUsableUrlAddress = NSMutableURLRequest(URL: usableUrlForRequest)

            mutableUrlWithUsableUrlAddress.addValue(authHeaders[TWTROAuthEchoAuthorizationHeaderKey] as? String, forHTTPHeaderField: "Authorization")

This sets the required Authorisation Key as a value for the "Authorization" header on the request, opposed to when you pass in the authHeaders dictionary, it gets set for "X-Verify-Credentials-Authorization".

The Fabric doc's do go into this, but it's slightly more tucked away than it should be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM