iOS开发:Intrinio API Basic认证失败问题求助
Fixing Intrinio API Authentication in Your iOS Code
Looks like you're missing the HTTP Basic Authentication header that Intrinio's API requires to verify your identity. That's why you can connect to the endpoint but can't pass authentication. Let's fix this step by step:
Step 1: Fill in Your Valid Credentials
First, replace the empty strings in your properties with your actual Intrinio developer username and password:
//MARK: - Properties let intrinioUsername = "YOUR_ACTUAL_USERNAME" // Your Intrinio username/API key let intrinioPassword = "YOUR_ACTUAL_PASSWORD" // Your Intrinio password (can be empty if using an API key as username)
Step 2: Add Authentication to Your API Request
You need to create a URLRequest object (instead of using the raw URL directly) so you can attach the authorization header. Here's the updated viewDidLoad code with authentication included:
override func viewDidLoad() { super.viewDidLoad() // Don't forget this critical lifecycle call! tickerTextField.textColor = UIColor.lightGray tickerTextField.text = "Search Ticker" tickerTextField.delegate = self // Note: You'll want to replace this hardcoded ticker with input from your text field later let ticker = "AAPL" let jsonUrlString = "https://api.intrinio.com/prices?identifier=\(ticker)" print(jsonUrlString) guard let url = URL(string: jsonUrlString) else { print("Invalid API URL") return } // Build the request and add authentication var request = URLRequest(url: url) // Encode credentials for Basic Auth let loginString = "\(intrinioUsername):\(intrinioPassword)" guard let loginData = loginString.data(using: .utf8) else { print("Failed to encode credentials") return } let base64LoginString = loginData.base64EncodedString() request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization") // Execute the authenticated request URLSession.shared.dataTask(with: request) { (data, response, err) in // Handle request errors first if let err = err { print("Request failed: \(err.localizedDescription)") return } // Check for authentication failure (401 status code) if let httpResponse = response as? HTTPURLResponse { print("Status code: \(httpResponse.statusCode)") if httpResponse.statusCode == 401 { print("Authentication failed - double-check your username/password") return } } guard let data = data else { print("No data returned from API") return } let dataAsString = String(data: data, encoding: .utf8) print(dataAsString ?? "Could not convert data to readable string") do { let jsonDecoder = JSONDecoder() let tickerPrice = try jsonDecoder.decode(TickerPrice.self, from: data) DispatchQueue.main.async { print(tickerPrice.name) // Update your UI (label, table view) here with the fetched data } } catch let jsonErr { print("Error parsing JSON: \(jsonErr)") } }.resume() }
Quick Additional Tips:
- Security First: Never hardcode credentials in production code. Use Apple's Keychain Services to store sensitive info like API credentials securely.
- Ticker Input: Right now the ticker is hardcoded to "AAPL". You'll want to update this to pull the value from your
tickerTextField(e.g., when the user taps a search button or finishes editing the field). - Error Handling: The updated code adds checks for common issues (invalid URLs, credential encoding failures, authentication errors) to help you debug faster.
内容的提问来源于stack exchange,提问作者MiastoVila
相关产品推荐
相关产品推荐

