初学者问题:Swift: NSMutableURLRequest

Beginners Question: Swift: NSMutableURLRequest

我有各种初学者错误,我无法修复。一些帮助将不胜感激。尝试 google 并阅读 apple 文档,但没有走得太远。这是代码部分:

import Foundation

struct StockDataManager  {

let headers = [
    "x-rapidapi-host": "yahoo-finance15.p.rapidapi.com",
    "x-rapidapi-key": "MYAPIKEY"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://yahoo-finance15.p.rapidapi.com/api/yahoo/qu/quote/AAPL/financial-data")! 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()

}

此时我得到以下错误:

request.httpMethod = "GET"

这里:

dataTask.resume()

我很确定这是基本的理解,对于这个愚蠢的简单问题深表歉意。在此先感谢您的帮助。

您不能拥有不是直接在结构中声明的代码 (request.httpMethod = "GET")。 将它嵌入到函数中,如下所示:

func setRequest() -> NSMutableURLRequest {
    let request = NSMutableURLRequest(
        url: NSURL(string: "https://yahoo-finance15.p.rapidapi.com/api/yahoo/qu/quote/AAPL/financial-data")! as URL,
        cachePolicy: .useProtocolCachePolicy,
        timeoutInterval: 10.0)
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers
    
    return request
}

首先,根本不要在 Swift 中使用 NSURLNS(Mutable)URLRequest。使用原生类型。

任何自定义代码都必须 运行 在一个函数内,例如

struct StockDataManager  {
    func loadData(completion: @escaping (Result<Data, Error>) -> Void) {
        let headers = [
            "x-rapidapi-host": "yahoo-finance15.p.rapidapi.com",
            "x-rapidapi-key": "MYAPIKEY"
        ]
        
        var request = URLRequest(url: URL(string: "https://yahoo-finance15.p.rapidapi.com/api/yahoo/qu/quote/AAPL/financial-data")!,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        
        request.httpMethod = "GET"
        request.allHTTPHeaderFields = headers
        
        let session = URLSession.shared
        let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
            if let error = error {
                completion(.failure(error))
            } else {
                let httpResponse = response as? HTTPURLResponse
                print(httpResponse)
                completion(.success(data!))
            }
        })
        dataTask.resume()
    }
}

loadData 函数还需要一个完成处理程序来处理异步接收的数据。