To provide an API key in Swift, you can use the Authorization header with Bearer authentication. Here's an example of how you can do it:

import Foundation

func makeRequest() {
    // API Key
    let apiKey = 'YOUR_API_KEY'
    
    // API Endpoint
    let url = URL(string: 'https://api.openai.com/v1/your-endpoint')!
    
    // Request
    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    request.addValue("Bearer (apiKey)", forHTTPHeaderField: "Authorization")
    
    // Send Request
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let error = error {
            print("Error: (error)")
            return
        }
        
        // Handle Response
        if let data = data {
            let responseString = String(data: data, encoding: .utf8)
            print("Response: (responseString ?? "")")
        }
    }
    
    task.resume()
}

// Call the function
makeRequest()

Make sure to replace 'YOUR_API_KEY' with your actual API key obtained from https://platform.openai.com/account/api-keys. Additionally, replace 'https://api.openai.com/v1/your-endpoint' with the appropriate API endpoint you want to access.

Swift OpenAI API Integration: Setting Up Authorization with API Key

原文地址: https://www.cveoy.top/t/topic/qm5p 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录