gpt4 book ai didi

swift : Twitter Application-Only Authentication

转载 作者:行者123 更新时间:2023-11-30 11:57:32 25 4
gpt4 key购买 nike

我正在构建一个应用程序,其中包含对我所在城市的某些商店的引用。现在,我想在每个商店的详细 View 中插入一个表格,其中包含该商店帐户的最后 3 或 5 条推文。

我不想使用第三方解决方案。

阅读 Twitter 的文档后,我了解到,要使用 Rest 服务,我必须对我的应用程序进行身份验证,因此我注册了该应用程序,并使用“只读”选项请求访问 token ,这里开始出现问题。

每次收到“身份验证错误”作为响应时,我都无法访问 Rest 服务。

Twitter 网站上的文档位于此处: https://developer.twitter.com/en/docs/basics/authentication/overview/application-only

其中描述了仅应用程序身份验证的三个步骤:

  1. 对消费者 key 和 secret 进行编码
  2. 获取不记名 token
  3. 使用不记名 token 对 API 请求进行身份验证

我在这里寻找解决方案:

然后在谷歌上我发现了这个: http://rshankar.com/retrieve-list-of-twitter-followers-using-swift/

这是我的尝试:

<强>1。首先,我创建了函数来编码consumer_key和consumer_secret

    let consumerKey = "xxxxxxxxxxxxxxxx"
let consumerSecret = "xxxxxxxxxxxxxxxx"
let authUrl = "https://api.twitter.com/oauth2/token"

func getBase64EncodeString() -> String {
let consumerKeyRFC1738 = consumerKey.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
let consumerSecretRFC1738 = consumerSecret.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
let concatenateKeyAndSecret = consumerKeyRFC1738! + ":" + consumerSecretRFC1738!
let secretAndKeyData = concatenateKeyAndSecret.data(using: String.Encoding.ascii, allowLossyConversion: true)
let base64EncodeKeyAndSecret = secretAndKeyData?.base64EncodedString(options: NSData.Base64EncodingOptions())
return base64EncodeKeyAndSecret!
}

<强>2。然后func获取bearerToken

    func getBearerToken(completion:@escaping (_ bearerToken: String) -> Void) {
var request = URLRequest(url: URL(string: authURL)!)
request.httpMethod = "POST"
request.addValue("Basic " + getBase64EncodeString(), forHTTPHeaderField: "Authorization")
request.addValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField:"Content-Type")
let grantType = "grant_type=client_credentials"
request.httpBody = grantType.data(using: String.Encoding.utf8, allowLossyConversion: true)
URLSession.shared.dataTask(with: request, completionHandler: { (data: Data?, response:URLResponse?, error: NSError?) -> Void in
do {
if let results: NSDictionary = try JSONSerialization .jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments ) as? NSDictionary {
if let token = results["access_token"] as? String {
completion(token)
} else {
print(results["errors"]!)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}
} as! (Data?, URLResponse?, Error?) -> Void).resume()
}

<强>3。最后使用不记名 token 对 API 请求进行身份验证

    func getResponseForRequest(url:String) {
var results:NSDictionary
getBearerToken(completion: { (bearerToken) -> Void in
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let token = "Bearer " + bearerToken
request.addValue(token, forHTTPHeaderField: "Authorization")
URLSession.shared .dataTask(with: request, completionHandler: { (data: Data?, response:URLResponse?, error: NSError?) -> Void in
self.processResult(data!, response: response!, error: error)
} as! (Data?, URLResponse?, Error?) -> Void).resume()
})
}

目前我在该行收到一条消息错误:

    } as! (Data?, URLResponse?, Error?) -> Void).resume()

在 getBearerToken 函数中。

错误信息是:

线程 1:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)

所以直到我还没有验证身份验证是否有效。

有人可以帮助我吗?

最佳答案

使用这个:

var request = URLRequest(url: url)
request.httpMethod = HttpMethod.POST.rawValue
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("Basic \(base64)", forHTTPHeaderField: "Authorization")
request.httpBody = "grant_type=client_credentials".data(using: .utf8)

关于 swift : Twitter Application-Only Authentication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47638740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com