[ad_1]
It is a follow-up to the next query: How one can name an occasion of a category that makes an API name, and a operate inside that class that makes the request, and assign this to variable? Swift.
I’m attempting to push a brand new view controller onto the stack, and current this view controller from an preliminary view controller, nonetheless after I run this system, the desk view that’s purported to be proven within the new view controller doesn’t load on the simulator. I haven’t got any error notifications from Xcode in any respect earlier than, throughout, or after operating this system. Additionally, it doesn’t seem to be code is being executed on this new view controller as a result of print statements on the high/very starting of the brand new view controller class (and consider controller .swift file) aren’t being printed.
What’s proven when the brand new desk view from the brand new view controller is meant to be proven is a clean display screen, however with the navigation bar nonetheless on the high, with the again button within the high left of the navigation bar (prefer it often is when the desk view was proven accurately earlier than altering to utilizing the YelpApi class for the API request and utilizing async/await). I am additionally not getting any error messages within the terminal when this happens.
What I feel is said to the issue is the brand new YelpApi class that’s getting used to make the API endpoint request right here, and utilizing async/await. This drawback didn’t happen till after I refactored my code utilizing this new class and async/await.
What I feel could also be inflicting the issue extra particularly, is I took out the “override” earlier than “func viewDidLoad() async {“ in NewViewController.swift. I did this as a result of I used to be getting an error when leaving it there, and located this resolution which steered to take it out, nonetheless, there’s a drawback with doing this as talked about within the feedback of the accepted reply (the issue being that there is no compile-time verify that ensures you’ve got acquired the signature proper): Swift protocols: methodology doesn’t override any methodology from its superclass.
I’ve already appeared this drawback (the desk view not displaying) up on-line together with right here, and couldn’t discover a working resolution. One related publish was this: View Controller not displaying correctly however my code is already arrange equally and in the identical type because the accepted reply. I’ve additionally let this system run for 20 minutes earlier than quitting this system in case the request was simply taking a very long time for no matter cause, nonetheless, the specified desk view nonetheless was not offered.
Code:
InitialViewController.swift:
//*Code for making a desk view that reveals choices to the consumer, for the consumer to pick.*
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//*Code for assigning values to variables associated to what row within the desk view the consumer chosen.*
let storyboard = UIStoryboard(title: "Fundamental", bundle: nil)
let newVC = storyboard.instantiateViewController(identifier: "NewViewController") as! NewViewController
newVC.modalPresentationStyle = .fullScreen
newVC.modalTransitionStyle = .crossDissolve
//Print Verify.
//Prints.
print("Print Verify: Proper earlier than code for presenting the brand new view controller.")
navigationController?.pushViewController(newVC, animated: true)
}
NewViewController.swift
import UIKit
import CoreLocation
class NewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//Print Verify.
//Would not print.
func printCheckBeforeIBOutletTableViewCode() {
print("Print Verify: Proper earlier than tableView IBOutlet code at high of NewViewController.swift file.")
}
@IBOutlet var tableView: UITableView!
var venues: [Venue] = []
//Print Verify.
//Would not print.
func printCheckAfterIBOutletTableViewCode() {
print("Print Verify: Proper after tableView IBOutlet code at high of NewViewController.swift file.")
}
func viewDidLoad() async {
tremendous.viewDidLoad()
//Perform requires print checks.
//Would not print.
self.printCheckBeforeIBOutletTableViewCode()
self.printCheckAfterIBOutletTableViewCode()
tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell")
tableView.delegate = self
tableView.dataSource = self
//Print Verify.
//Would not print.
print("Print Verify: Proper earlier than creating an occasion of YelpApi class, then making a activity to make the API request.")
let yelpApi = YelpApi(apiKey: "Api key")
Job {
do {
self.venues = strive await yelpApi.searchBusiness(latitude: selectedLatitude, longitude: selectedLongitude, class: "class quary goes right here", sortBy: "type by quary goes right here")
self.tableView.reloadData()
} catch {
//Deal with error right here.
print("Error")
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection part: Int) -> Int {
return venues.depend
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
//Particulars for customized desk view cell go right here.
}
//Remainder of desk view protocol capabilities.
}
Venue.swift:
import Basis
// MARK: - BusinessSearchResult
struct BusinessSearchResult: Codable {
let complete: Int
let companies: [Venue]
let area: Area
}
// MARK: - Enterprise
struct Venue: Codable {
let score: Double
let value, telephone, alias: String?
let id: String
let isClosed: Bool?
let classes: [Category]
let reviewCount: Int?
let title: String
let url: String?
let coordinates: Middle
let imageURL: String?
let location: Location
let distance: Double
let transactions: [String]
enum CodingKeys: String, CodingKey {
case score, value, telephone, id, alias
case isClosed
case classes
case reviewCount
case title, url, coordinates
case imageURL
case location, distance, transactions
}
}
// MARK: - Class
struct Class: Codable {
let alias, title: String
}
// MARK: - Middle
struct Middle: Codable {
let latitude, longitude: Double
}
// MARK: - Location
struct Location: Codable {
let metropolis, nation, address2, address3: String?
let state, address1, zipCode: String?
enum CodingKeys: String, CodingKey {
case metropolis, nation, address2, address3, state, address1
case zipCode
}
}
// MARK: - Area
struct Area: Codable {
let heart: Middle
}
FetchData.swift:
import Basis
import CoreLocation
class YelpApi {
personal var apiKey: String
init(apiKey: String) {
self.apiKey = apiKey
}
func searchBusiness(latitude: Double,
longitude: Double,
class: String,
sortBy: String) async throws -> [Venue] {
var queryItems = [URLQueryItem]()
queryItems.append(URLQueryItem(title:"latitude",worth:"(latitude)"))
queryItems.append(URLQueryItem(title:"longitude",worth:"(longitude)"))
queryItems.append(URLQueryItem(title:"classes", worth:class))
queryItems.append(URLQueryItem(title:"sort_by",worth:sortBy))
var outcomes = [Venue]()
var expectedCount = 0
let countLimit = 50
var offset = 0
queryItems.append(URLQueryItem(title:"restrict", worth:"(countLimit)"))
repeat {
var offsetQueryItems = queryItems
offsetQueryItems.append(URLQueryItem(title:"offset",worth: "(offset)"))
var urlComponents = URLComponents(string: "https://api.yelp.com/v3/companies/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 (knowledge, _) = strive await URLSession.shared.knowledge(for: request)
let businessResults = strive JSONDecoder().decode(BusinessSearchResult.self, from:knowledge)
expectedCount = min(businessResults.complete,1000)
outcomes.append(contentsOf: businessResults.companies)
offset += businessResults.companies.depend
} whereas (outcomes.depend < expectedCount)
return outcomes
}
}
Thanks!
[ad_2]
