I have a usernameTextField in the viewController where I enter a username and a button searchTapped with the following code:
@IBAction func searchTapped(_ sender: UIButton) {
guard let username = usernameTextField.text, username != "" else {
displayWarningLabel(withText: "Information is incorrect")
return
}
guard let gitUrl = URL(string: "https://api.github.com/users/\(username)/gists") else { return }
URLSession.shared.dataTask(with: gitUrl) { (data, response, error) in
guard let data = data else { return }
guard error == nil else { return }
do {
let gitData = try JSONDecoder().decode([Gists].self, from: data)
DispatchQueue.main.async {
self.gists = gitData
}
} catch let error {
print(error)
}
}.resume()
performSegue(withIdentifier: "GistsSegue", sender: nil)
}
after I get the data from json I want to save the data into an array gists outside of this method, but this does not happen.
var gists = [Gists]()
What could be the problem?
Just in case, this is my model for parsing json:
struct Gists: Codable {
var description: String?
var files: [String: DetailGist]
}
struct DetailGist: Codable {
var filename: String?
var raw_url: String?
}
self.gists = gitData
is being called but it is called long after you call performSegue
. This is the nature of asynchronous data access.
Simply move your performSegue
call to be just after you set self.gists
.
DispatchQueue.main.async {
self.gists = gitData
performSegue(withIdentifier: "GistsSegue", sender: nil)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.