這是以下問題的后續:如何呼叫進行 API 呼叫的類的實體,以及該類中發出請求的函式,并將其分配給變數?斯威夫特。
我正在嘗試將新的視圖控制器推送到堆疊上,并從初始視圖控制器中呈現此視圖控制器,但是當我運行程式時,應該在新視圖控制器中顯示的表視圖不會加載在模擬器上。在運行程式之前、期間或之后,我根本沒有來自 Xcode 的任何錯誤通知。此外,似乎沒有在這個新的視圖控制器中執行代碼,因為新視圖控制器類(和視圖控制器 .swift 檔案)的頂部/最開頭的列印陳述句沒有被列印。
當應該顯示來自新視圖控制器的新表視圖時顯示的是一個空白螢屏,但導航欄仍在頂部,導航欄左上方的后退按鈕(通常是在更改為對 API 請求使用 YelpApi 類并使用 async/await 之前正確顯示表視圖時)。發生這種情況時,我也沒有在終端中收到任何錯誤訊息。
我認為與該問題相關的是新的 YelpApi 類,該類用于在此處發出 API 端點請求,并使用 async/await。直到我使用這個新類和 async/await 重構了我的代碼之后,這個問題才出現。
我認為可能導致問題更具體的原因是,我在 NewViewController.swift 中的“func viewDidLoad() async {”之前取出了“覆寫”。我這樣做是因為我把它放在那里時遇到了一個錯誤,并找到了建議將其取出的解決方案,但是,如已接受答案的評論中所述,這樣做存在問題(問題是沒有編譯時檢查以確保您的簽名正確):Swift 協議:方法不會覆寫其超類中的任何方法。
我已經在網上(包括此處)查看了這個問題(表格視圖未顯示),但找不到有效的解決方案。一篇類似的帖子是這樣的:View Controller 沒有正確顯示,但我的代碼已經以與接受的答案類似的形式設定。我還讓程式在退出程式之前運行了 20 分鐘,以防請求因某種原因而花費很長時間,但是仍然沒有顯示所需的表格視圖。
代碼:
InitialViewController.swift:
//*Code for creating a table view that shows options to the user, for the user to select.*
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//*Code for assigning values to variables related to what row in the table view the user selected.*
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let newVC = storyboard.instantiateViewController(identifier: "NewViewController") as! NewViewController
newVC.modalPresentationStyle = .fullScreen
newVC.modalTransitionStyle = .crossDissolve
//Print Check.
//Prints.
print("Print Check: Right before code for presenting the new view controller.")
navigationController?.pushViewController(newVC, animated: true)
}
NewViewController.swift
import UIKit
import CoreLocation
class NewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//Print Check.
//Doesn't print.
func printCheckBeforeIBOutletTableViewCode() {
print("Print Check: Right before tableView IBOutlet code at top of NewViewController.swift file.")
}
@IBOutlet var tableView: UITableView!
var venues: [Venue] = []
//Print Check.
//Doesn't print.
func printCheckAfterIBOutletTableViewCode() {
print("Print Check: Right after tableView IBOutlet code at top of NewViewController.swift file.")
}
func viewDidLoad() async {
super.viewDidLoad()
//Function calls for print checks.
//Doesn't print.
self.printCheckBeforeIBOutletTableViewCode()
self.printCheckAfterIBOutletTableViewCode()
tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell")
tableView.delegate = self
tableView.dataSource = self
//Print Check.
//Doesn't print.
print("Print Check: Right before creating an instance of YelpApi class, then creating a task to make the API request.")
let yelpApi = YelpApi(apiKey: "Api key")
Task {
do {
self.venues = try await yelpApi.searchBusiness(latitude: selectedLatitude, longitude: selectedLongitude, category: "category quary goes here", sortBy: "sort by quary goes here")
self.tableView.reloadData()
} catch {
//Handle error here.
print("Error")
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return venues.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
//Details for custom table view cell go here.
}
//Rest of table view protocol functions.
}
Venue.swift:
import Foundation
// MARK: - BusinessSearchResult
struct BusinessSearchResult: Codable {
let total: Int
let businesses: [Venue]
let region: Region
}
// MARK: - Business
struct Venue: Codable {
let rating: Double
let price, phone, alias: String?
let id: String
let isClosed: Bool?
let categories: [Category]
let reviewCount: Int?
let name: String
let url: String?
let coordinates: Center
let imageURL: String?
let location: Location
let distance: Double
let transactions: [String]
enum CodingKeys: String, CodingKey {
case rating, price, phone, id, alias
case isClosed
case categories
case reviewCount
case name, url, coordinates
case imageURL
case location, distance, transactions
}
}
// MARK: - Category
struct Category: Codable {
let alias, title: String
}
// MARK: - Center
struct Center: Codable {
let latitude, longitude: Double
}
// MARK: - Location
struct Location: Codable {
let city, country, address2, address3: String?
let state, address1, zipCode: String?
enum CodingKeys: String, CodingKey {
case city, country, address2, address3, state, address1
case zipCode
}
}
// MARK: - Region
struct Region: Codable {
let center: Center
}
FetchData.swift:
import Foundation
import CoreLocation
class YelpApi {
private var apiKey: String
init(apiKey: String) {
self.apiKey = apiKey
}
func searchBusiness(latitude: Double,
longitude: Double,
category: String,
sortBy: String) async throws -> [Venue] {
var queryItems = [URLQueryItem]()
queryItems.append(URLQueryItem(name:"latitude",value:"\(latitude)"))
queryItems.append(URLQueryItem(name:"longitude",value:"\(longitude)"))
queryItems.append(URLQueryItem(name:"categories", value:category))
queryItems.append(URLQueryItem(name:"sort_by",value:sortBy))
var results = [Venue]()
var expectedCount = 0
let countLimit = 50
var offset = 0
queryItems.append(URLQueryItem(name:"limit", value:"\(countLimit)"))
repeat {
var offsetQueryItems = queryItems
offsetQueryItems.append(URLQueryItem(name:"offset",value: "\(offset)"))
var urlComponents = URLComponents(string: "https://api.yelp.com/v3/businesses/search")
urlComponents?.queryItems = offsetQueryItems
guard let url = urlComponents?.url else {
throw URLError(.badURL)
}
var request = URLRequest(url: url)
request.setValue("Bearer \(self.apiKey)", forHTTPHeaderField: "Authorization")
let (data, _) = try await URLSession.shared.data(for: request)
let businessResults = try JSONDecoder().decode(BusinessSearchResult.self, from:data)
expectedCount = min(businessResults.total,1000)
results.append(contentsOf: businessResults.businesses)
offset = businessResults.businesses.count
} while (results.count < expectedCount)
return results
}
}
謝謝!
更新:
在根據 Andreas 和 Paulw11 的建議進行更改后,運行程式時表格視圖仍然沒有加載,并且我在創建 YelpApi 類的實體之后的catch塊中的終端中的最后一個列印陳述句是“錯誤”Task在 中發出初始 API 請求NewViewController.swift。我已經將檔案中的這個“錯誤”陳述句更改為“發出初始 API 端點請求時發生錯誤”。為了清楚起見。
NewViewController.swift以下是Andreas 和 Paulw11 建議的更改的更新版本,以及FetchData.swift用于幫助識別新問題的新列印宣告。在這些更新版本的下方是在做出 Andreas 和 Paulw11 的建議更改后來自終端的回傳陳述句,其中還包含 FetchData.swift 更新版本中的新列印陳述句(用于幫助識別新問題)。
插入和取出NewViewController.swift的更新版本:overrideasync
import UIKit
import CoreLocation
class NewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//Print Check.
//Prints.
func printCheckBeforeIBOutletTableViewCode() {
print("Print Check: Right before tableView IBOutlet code at top of NewViewController.swift file.")
}
@IBOutlet var tableView: UITableView!
var venues: [Venue] = []
//Print Check.
//Prints.
func printCheckAfterIBOutletTableViewCode() {
print("Print Check: Right after tableView IBOutlet code at top of NewViewController.swift file.")
}
override func viewDidLoad() {
super.viewDidLoad()
//Function calls for print checks.
//Prints.
self.printCheckBeforeIBOutletTableViewCode()
self.printCheckAfterIBOutletTableViewCode()
tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell")
tableView.delegate = self
tableView.dataSource = self
//Print Check.
//Prints.
print("Print Check: Right before creating an instance of YelpApi class, then creating a task to make the API request.")
let yelpApi = YelpApi(apiKey: "Api key")
Task {
do {
self.venues = try await yelpApi.searchBusiness(latitude: selectedLatitude, longitude: selectedLongitude, category: "category quary goes here", sortBy: "sort by quary goes here")
self.tableView.reloadData()
} catch {
//Handle error here.
//Prints.
print("Error")
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return venues.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
//Details for custom table view cell go here.
}
//Rest of table view protocol functions.
}
更新版本FetchData.swift包括新的列印陳述句以幫助識別新問題:
import Foundation
import CoreLocation
class YelpApi {
private var apiKey: String
init(apiKey: String) {
self.apiKey = apiKey
}
func searchBusiness(latitude: Double,
longitude: Double,
category: String,
sortBy: String) async throws -> [Venue] {
var queryItems = [URLQueryItem]()
queryItems.append(URLQueryItem(name:"latitude",value:"\(latitude)"))
queryItems.append(URLQueryItem(name:"longitude",value:"\(longitude)"))
queryItems.append(URLQueryItem(name:"categories", value:category))
queryItems.append(URLQueryItem(name:"sort_by",value:sortBy))
var results = [Venue]()
var expectedCount = 0
let countLimit = 50
var offset = 0
queryItems.append(URLQueryItem(name:"limit", value:"\(countLimit)"))
//Print Check.
//Prints.
print("Print Check: Line before repeat-while loop.")
repeat {
//Print Check.
//Prints.
print("Print Check: Within repeat-while loop and before first line of code within it.")
var offsetQueryItems = queryItems
offsetQueryItems.append(URLQueryItem(name:"offset",value: "\(offset)"))
var urlComponents = URLComponents(string: "https://api.yelp.com/v3/businesses/search")
urlComponents?.queryItems = offsetQueryItems
guard let url = urlComponents?.url else {
throw URLError(.badURL)
}
var request = URLRequest(url: url)
request.setValue("Bearer \(self.apiKey)", forHTTPHeaderField: "Authorization")
//Print Check.
//Prints.
print("Print Check: Within repeat-while loop and before 'let (data, _) = try await' line of code.")
let (data, _) = try await URLSession.shared.data(for: request)
//Print Check.
//Prints.
print("Print Check: Within repeat-while loop and before 'let businessResults = try JSONDecoder()' line of code.")
let businessResults = try JSONDecoder().decode(BusinessSearchResult.self, from:data)
//Print Check.
//Doesn't print.
print("Print Check: Within repeat-while loop and right after 'let businessResults = try JSONDecoder()' line of code.")
expectedCount = min(businessResults.total,1000)
results.append(contentsOf: businessResults.businesses)
offset = businessResults.businesses.count
} while (results.count < expectedCount)
//Print Check.
//Doesn't print.
print("Print Check: After repeat-while loop and before 'return results' code.")
return results
}
}
Returned Print Statements from Terminal Returned After Making Andreas and Paulw11's Suggested Changes and Running Program:
Print Check: Right before code for presenting the new view controller.
Print Check: Right before tableView IBOutlet code at top of NewViewController.swift file.
Print Check: Right after tableView IBOutlet code at top of NewViewController.swift file.
Print Check: Right before creating an instance of YelpApi class, then creating a task to make the API request.
Print Check: Line before repeat-while loop.
Print Check: Within repeat-while loop and before first line of code within it.
Print Check: Within repeat-while loop and before 'let (data, _) = try await' line of code.
Date and Time, Project Name, and some other info [boringssl] boringssl_metrics_log_metric_block_invoke(153) Failed to log metrics
Print Check: Within repeat-while loop and before 'let businessResults = try JSONDecoder()' line of code.
Error occurred when making initial API endpoint request.
不得不退出程式,因為它“停止”/在終端中做出上面的最后一個列印陳述句后什么也沒做。
此外,每當我提出 API 請求時,都會出現“日期和時間、專案名稱和其他一些資訊 [boringssl]boringssl_metrics_log_metric_block_invoke(153) 無法記錄指標”列印陳述句,并且在研究時不會對專案。
在“發出初始 API 端點請求時發生錯誤”之前列印的最后一條列印陳述句。正在“列印檢查:在重復回圈內和'讓 businessResults = 嘗試 JSONDecoder()' 代碼行之前。” 表明代碼行出現let businessResults = try JSONDecoder().decode(BusinessSearchResult.self, from:data)問題,這使我認為問題可能正在發生,并且與在類定義的函式中附加quarryItemsforcategory和時有關。我正在努力解決這個問題,如果我解決了這個問題,我會更新。sort_bysearchBusinessesYelpApiFetchData.swift
感謝所有的幫助!
uj5u.com熱心網友回復:
我認為您已經確定了其中一個問題。你的代碼func viewDidLoad() async永遠不會被執行,因為沒有人呼叫它。通過添加async,您不再覆寫原始UIViewController方法。(請參閱https://developer.apple.com/documentation/uikit/uiviewcontroller/1621495-viewdidload)您可以洗掉async并再次覆寫它嗎?我認為這至少應該執行代碼,你應該看到你的列印陳述句。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486945.html
標籤:IOS 迅速 异步等待 视图控制器 yelp-融合-api
上一篇:Swift在范圍內找不到變數
