URLSession 在错误和状态代码的范围内找不到"self"



我的问题与69959018有点相似,所以我已经尽可能多地澄清

我正在尝试使用Steam Web API创建一个应用程序,以JSON字典的形式抓住我朋友列表中的每个人。为了更好地学习基金会,我试着用基金会而不是阿拉莫菲尔。

到目前为止,我在AppDelegate.swift中做了以下工作:

class AppDelegate: NSObject, NSApplicationDelegate { 
func applicationDidFinishLaunching(_ aNotification: Notification) {
var apiKey: String = "[REDACTED]"
var steamID: String = "[REDACTED]"
let getPlayerSummaries = URL(string: "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=(apiKey)&steamids=(steamID)")

let friendList = downloadPlayerSummaries(with: getPlayerSummaries) 
print(friendList)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
return true
}
}

在我制作的另一个名为networkManager.swift的文件中,我根据我在苹果文档中发现的";将网站数据提取到存储器中":

//
//  networkManager.swift
//  Who is online?
//
//  Created by Dash Interwebs on 11/21/21.
//
import Foundation

func downloadPlayerSummaries(with: URL!) {
let url = with
if url == nil {
print("url is nil")
return
}
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
if let error = error {
self.handleClientError(error)
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
self.handleServerError(response)
return
}

}
}
task.resume()
}

然而,在这之后,self.handleClientError(error)self.handleServerError(response)抱怨不能找到";自我";。我找不到有关handleServerError或handleClientError的任何信息。那么";自我;在这种情况下?我想这可能是URLSession,但我不太确定。

您可以使用完成处理程序和符合Error协议的枚举来重构代码:

enum ApiError:错误{案例网络(错误(case genericErrorcase httpResponseError}

func downloadPlayerSummaries(with url: URL?, completion: @escaping (_ success: Bool, _ error: ApiError?) -> Void) {
guard let url = url else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
completion(false, .network(error))
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
completion(false, .httpResponseError)
return
}
// then handle your data. The completion should also include the kind of data your want to return 
}
task.resume()
}

我还没有测试。如果有效,请告诉我。

相关内容

  • 没有找到相关文章

最新更新