无法执行 URL 请求 SWIFT

Can't Perform a URL Request SWIFT

我正在尝试进行 API 调用,但它向我抛出状态代码 401(这是未经授权的客户端响应)我无法访问那里的 JSON 数据。我已经通过表示 PostMan 数据尝试了我的 API 键。也许我遗漏了什么。

MARK: - 错误示例 状态代码应为 2xx 但为 401 - 状态代码表示基于以下内容。

guard response.statusCode >= 200 && response.statusCode < 300 else {
            print("Status code should be 2xx but is \(response.statusCode)")
            return
        }

马克:- 我的代码

   func fetchDat() {

    guard let url = URL(string: "https://odds.p.rapidapi.com/v1/sports") else { return }

    var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
    request.httpMethod = "GET"
    request.setValue("c15b711e56msh05b5f41ea7d8e5dp1b1b56jsne1f975246c84", forHTTPHeaderField: "x-rapidapi-key")
    
    downloadData(fromURL: url) { returnedData in
        if let data = returnedData {
            //MARK: - JSON Decoder
            guard let newPosts = try? JSONDecoder().decode([Result].self, from: data) else { return }
                DispatchQueue.main.async { [weak self] in
                    self?.res = newPosts
                }
        } else {
            print("No data returned")
        }
    }
    
}

func downloadData(fromURL url: URL, completionHandler: @escaping(_ data: Data?) -> Void) {
    
    //MARK: - URL Session Error, data, Response Handler
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        
        //MARK: - More Recommended Method
        guard
            let data = data,
            error == nil,
            let response = response as? HTTPURLResponse,
                response.statusCode >= 200 && response.statusCode < 300 else {
            print("Error Downloading Data")
            completionHandler(nil)
            return
            }
    completionHandler(data)
        }.resume()
    
    }

}

Bellow MARK: - 快速 API NSURLSESSION 访问模板

import Foundation

let headers = [
    "x-rapidapi-host": "odds.p.rapidapi.com",
    "x-rapidapi-key": "c15b711e56msh05b5f41ea7d8e5dp1b1b56jsne1f975246c84"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://odds.p.rapidapi.com/v1/sports")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        print(error)
    } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse)
    }
})

dataTask.resume()

您可以参考下面的屏幕截图,我的 POSTMAN header 正在工作并且 link 本身正在工作。

我已经更新了我的代码,现在它看起来像这样:

func fetchDat() {
        
        
//        guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return }
        guard let url = URL(string: "https://odds.p.rapidapi.com/v1/sports") else { return }
        var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
        request.httpMethod = "GET"
        request.setValue("c15b711e56msh05b5f41ea7d8e5dp1b1b56jsne1f975246c84", forHTTPHeaderField: "x-rapidapi-key")
        request.setValue("odds.p.rapidapi.com", forHTTPHeaderField: "x-rapidapi-host")
        
            URLSession.shared.dataTask(with: request) { (data, response, error) in

     
                guard let data = data else {
                    print("No Data.")
                    return
                }
                
                guard error == nil else  {
                    print("Error: \(String(describing: error))")
                    return
                }
                guard let response = response as? HTTPURLResponse else {
                    print("Invalid Response")
                    return
                }
                guard response.statusCode >= 200 && response.statusCode < 300 else {

                print("Status code should be 2xx but is \(response.statusCode)")
                            
                        return
                    }
                    
                    guard let newPosts = try? JSONDecoder().decode([Result].self, from: data) else { return }
                    DispatchQueue.main.async { [weak self] in
                        self?.res = newPosts
                    }
    }.resume()
}
        
    }

您正在设置 request.setValue("API KEY", forHTTPHeaderField: "Authorization")。但是,在示例代码中,API 期待您的 API 密钥位于名称 x-rapidapi-key 下。因此 request.setValue("API KEY", forHTTPHeaderField: "x-rapidapi-key") 应该有效。当然不要忘记将自己的Key正确插入占位符中。