我要求的JSON页面需要密码和用户名都是字符串类型。用户名和密码属于开发人员...顺便说一下,它能够到达页面,我无法通过身份验证。
这是api url:https://api.intrinio.com/prices?identifier=AAPL
如果我遗漏了一些信息或代码,请告诉我,我会提供。
class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {
//MARK: - Outlets
@IBOutlet weak var labelTwo: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tickerTextField: UITextField!
//MARK: - Properties
let userPasswordString = ""
let userPassword = ""
//MARK: - View Did Load
override func viewDidLoad() {
tickerTextField.textColor = UIColor.lightGray
tickerTextField.text = "Search Ticker"
tickerTextField.delegate = self
let jsonUrlString = "https://api.intrinio.com/prices?identifier=\(ticker)"
print(jsonUrlString)
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
let dataAsString = String(data: data!, encoding: .utf8)
print(dataAsString!)
guard let data = data else { return }
do {
let jsonDecoder = JSONDecoder()
let tickerPrice = try jsonDecoder.decode(TickerPrice.self, from: data)
DispatchQueue.main.async {
print(tickerPrice.name)
}
} catch let jsonErr {
print("Error serielaising jason", jsonErr)
}
}.resume()
}
答案 0 :(得分:0)
私人授权您访问Intrinio API:
// With shell, you must include the username and // password header curl "https://api.intrinio.com/data_point?identifier=AAPL&item=close_price" -u "API_USERNAME:API_PASSWORD" // With the '-u' option in curl, it will automatically // convert the username and password into the // appropriate header. If you do not use this // option or it is not available to you, you must // include a header with the basic auth credentials // included as base64 encoded. curl "https://api.intrinio.com/data_point?identifier=AAPL&item=close_price" -H "Authorization: Basic $BASE64_ENCODED(API_USERNAME:API_PASSWORD)"
对于私有/受信任环境,请使用基于HTTPS的基本身份验证。
您可以在“帐户”页面上找到API用户名和API密码。 您必须在每个请求中包含这些凭据 获得对API的访问权。
要在HTTPS请求中包含凭据,请指定 授权标头,值为Basic(键),替换(键) Base-64编码的字符串API_USERNAME:API_PASSWORD。
如果您的凭据未经授权,则状态代码为401 返回。
您必须使用API密钥替换API_USERNAME和API_PASSWORD 可在API管理控制台上找到。
为此,您需要使用URLRequest
,而不仅仅是URL
:
//Create URLRequest
var request = URLRequest.init(url: url!)
//Create Header according to the documentation
let userName = "API_USERNAME" //Need to be replaced with correct value
let password = "API_PASSWORD" //Need to be replaced with correct value
let toEncode = "\(userName):\(password)" //Form the String to be encoded
let encoded = toEncode.data(using: .utf8)?.base64EncodedString()
//Add the header value
request.addValue("Basic \(encoded!)", forHTTPHeaderField: "Authorization")
//Perform the task with the request instead of previously the URL
URLSession.shared.dataTask(with: request){//The rest of your code}
旁注,我没有guard let
或if let
,我在需要时难以打开。它是显示主要逻辑和CocoaTouch API而不是其他任何东西,特别是因为我不是Swift开发人员。