我正在构建一个应用程序,其中包含对我所在城市的某些商店的引用。现在,我想在每个商店的详细信息中插入一张带有商店帐户中最后3或5条推文的桌子。
我不想使用第三方解决方案。
阅读Twitter的文档,我知道,要使用我必须对应用程序进行身份验证的其余服务,因此我已经注册了该应用程序并请求使用"仅读取"选项的访问令牌,并在这里开始问题。
。每当我将"身份验证错误"作为响应时,我将无法访问休息服务。
Twitter网站上的文档在这里:https://developer.twitter.com/en/docs/basics/authentication/authentication/overview/application-anly-nolly
其中描述了仅应用程序auth的三个步骤:
- 编码消费者密钥和秘密
- 获取一个携带者令牌
- 用携带者令牌身份验证API请求
我在这里寻找解决方案:
- 使用Swift 访问Twitter
- Twitter友谊/创建API要求在Swift中进行身份验证
- 用Twitterkit在Swift中解析Twitter API搜索响应
然后在Google上发现了这一点:http://rshankar.com/retrieve-list-of-twitter-followers-using-swift/
这是我的尝试:
1。首先,我创建了func来编码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。然后获取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。最后,用携带者令牌
对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 func中。
错误消息是:
线程1:exc_bad_instruction(code = exc_i386_invop,subcode = 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)