Array that's supposed to store JSON is empty after successful JSON parsing
var pokemons = [Pokemon]()
func loadJSON() {
let url = "https://pokeapi.co/api/v2/pokemon/"
guard let urlObj = URL(string: url) else { return }
URLSession.shared.dataTask(with: urlObj) {(data, response, error) in
guard let data = data else { return }
do {
let pokedex = try JSONDecoder().decode(Pokedex.self, from: data)
for pokemon in pokedex.results {
guard let jsonURL = pokemon.url else { return }
guard let newURL = URL(string: jsonURL) else { return }
URLSession.shared.dataTask(with: newURL) {(data, response, error) in
guard let data = data else { return }
do {
let load = try JSONDecoder().decode(Pokemon.self, from: data)
self.pokemons.append(load)
} catch let jsonErr {
print("Error serializing inner JSON:", jsonErr)
}
}.resume()
}
} catch let jsonErr{
print("Error serializing JSON: ", jsonErr)
}
}.resume()
}
This code compiles and runs fine, but the array pokemons returns a count of 0 when I check its size afterwards. It's strange because if I loop through the array right after the pokemons.append(load), it'll spit out a bunch of data. It's as if the data gets lost as soon as it's out of scope of the JSON. Does my array need to be passed by reference or something? I'm looking to take the data and put it into a UITableView, but so far nothing is showing.
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Pokemon"
navigationController?.navigationBar.prefersLargeTitles = true
loadJSON()
print(pokemons.count) //Prints 0
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label = UILabel()
label.text = "By Id"
label.backgroundColor = UIColor.lightGray
return label
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pokemons.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let name = pokemons[indexPath.row].name
cell.textLabel?.text = "(name) Section:(indexPath.section) Row:(indexPath.row)"
return cell
}
ios iphone swift
add a comment |
var pokemons = [Pokemon]()
func loadJSON() {
let url = "https://pokeapi.co/api/v2/pokemon/"
guard let urlObj = URL(string: url) else { return }
URLSession.shared.dataTask(with: urlObj) {(data, response, error) in
guard let data = data else { return }
do {
let pokedex = try JSONDecoder().decode(Pokedex.self, from: data)
for pokemon in pokedex.results {
guard let jsonURL = pokemon.url else { return }
guard let newURL = URL(string: jsonURL) else { return }
URLSession.shared.dataTask(with: newURL) {(data, response, error) in
guard let data = data else { return }
do {
let load = try JSONDecoder().decode(Pokemon.self, from: data)
self.pokemons.append(load)
} catch let jsonErr {
print("Error serializing inner JSON:", jsonErr)
}
}.resume()
}
} catch let jsonErr{
print("Error serializing JSON: ", jsonErr)
}
}.resume()
}
This code compiles and runs fine, but the array pokemons returns a count of 0 when I check its size afterwards. It's strange because if I loop through the array right after the pokemons.append(load), it'll spit out a bunch of data. It's as if the data gets lost as soon as it's out of scope of the JSON. Does my array need to be passed by reference or something? I'm looking to take the data and put it into a UITableView, but so far nothing is showing.
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Pokemon"
navigationController?.navigationBar.prefersLargeTitles = true
loadJSON()
print(pokemons.count) //Prints 0
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label = UILabel()
label.text = "By Id"
label.backgroundColor = UIColor.lightGray
return label
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pokemons.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let name = pokemons[indexPath.row].name
cell.textLabel?.text = "(name) Section:(indexPath.section) Row:(indexPath.row)"
return cell
}
ios iphone swift
1
loadJSON
is asynchronous.
– rmaddy
Nov 25 '18 at 16:30
hey! sorry I'm not familiar with what that means. Could you explain more?
– teachMeSenpai
Nov 25 '18 at 16:35
add a comment |
var pokemons = [Pokemon]()
func loadJSON() {
let url = "https://pokeapi.co/api/v2/pokemon/"
guard let urlObj = URL(string: url) else { return }
URLSession.shared.dataTask(with: urlObj) {(data, response, error) in
guard let data = data else { return }
do {
let pokedex = try JSONDecoder().decode(Pokedex.self, from: data)
for pokemon in pokedex.results {
guard let jsonURL = pokemon.url else { return }
guard let newURL = URL(string: jsonURL) else { return }
URLSession.shared.dataTask(with: newURL) {(data, response, error) in
guard let data = data else { return }
do {
let load = try JSONDecoder().decode(Pokemon.self, from: data)
self.pokemons.append(load)
} catch let jsonErr {
print("Error serializing inner JSON:", jsonErr)
}
}.resume()
}
} catch let jsonErr{
print("Error serializing JSON: ", jsonErr)
}
}.resume()
}
This code compiles and runs fine, but the array pokemons returns a count of 0 when I check its size afterwards. It's strange because if I loop through the array right after the pokemons.append(load), it'll spit out a bunch of data. It's as if the data gets lost as soon as it's out of scope of the JSON. Does my array need to be passed by reference or something? I'm looking to take the data and put it into a UITableView, but so far nothing is showing.
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Pokemon"
navigationController?.navigationBar.prefersLargeTitles = true
loadJSON()
print(pokemons.count) //Prints 0
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label = UILabel()
label.text = "By Id"
label.backgroundColor = UIColor.lightGray
return label
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pokemons.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let name = pokemons[indexPath.row].name
cell.textLabel?.text = "(name) Section:(indexPath.section) Row:(indexPath.row)"
return cell
}
ios iphone swift
var pokemons = [Pokemon]()
func loadJSON() {
let url = "https://pokeapi.co/api/v2/pokemon/"
guard let urlObj = URL(string: url) else { return }
URLSession.shared.dataTask(with: urlObj) {(data, response, error) in
guard let data = data else { return }
do {
let pokedex = try JSONDecoder().decode(Pokedex.self, from: data)
for pokemon in pokedex.results {
guard let jsonURL = pokemon.url else { return }
guard let newURL = URL(string: jsonURL) else { return }
URLSession.shared.dataTask(with: newURL) {(data, response, error) in
guard let data = data else { return }
do {
let load = try JSONDecoder().decode(Pokemon.self, from: data)
self.pokemons.append(load)
} catch let jsonErr {
print("Error serializing inner JSON:", jsonErr)
}
}.resume()
}
} catch let jsonErr{
print("Error serializing JSON: ", jsonErr)
}
}.resume()
}
This code compiles and runs fine, but the array pokemons returns a count of 0 when I check its size afterwards. It's strange because if I loop through the array right after the pokemons.append(load), it'll spit out a bunch of data. It's as if the data gets lost as soon as it's out of scope of the JSON. Does my array need to be passed by reference or something? I'm looking to take the data and put it into a UITableView, but so far nothing is showing.
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Pokemon"
navigationController?.navigationBar.prefersLargeTitles = true
loadJSON()
print(pokemons.count) //Prints 0
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label = UILabel()
label.text = "By Id"
label.backgroundColor = UIColor.lightGray
return label
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pokemons.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let name = pokemons[indexPath.row].name
cell.textLabel?.text = "(name) Section:(indexPath.section) Row:(indexPath.row)"
return cell
}
ios iphone swift
ios iphone swift
asked Nov 25 '18 at 16:28
teachMeSenpaiteachMeSenpai
617
617
1
loadJSON
is asynchronous.
– rmaddy
Nov 25 '18 at 16:30
hey! sorry I'm not familiar with what that means. Could you explain more?
– teachMeSenpai
Nov 25 '18 at 16:35
add a comment |
1
loadJSON
is asynchronous.
– rmaddy
Nov 25 '18 at 16:30
hey! sorry I'm not familiar with what that means. Could you explain more?
– teachMeSenpai
Nov 25 '18 at 16:35
1
1
loadJSON
is asynchronous.– rmaddy
Nov 25 '18 at 16:30
loadJSON
is asynchronous.– rmaddy
Nov 25 '18 at 16:30
hey! sorry I'm not familiar with what that means. Could you explain more?
– teachMeSenpai
Nov 25 '18 at 16:35
hey! sorry I'm not familiar with what that means. Could you explain more?
– teachMeSenpai
Nov 25 '18 at 16:35
add a comment |
1 Answer
1
active
oldest
votes
You either need
self.pokemons.append(load)
DispatchQueue.main.async {
self.tableView.reloadData()
}
or write a completion
the asynchronous call is something that doesn't go in serial with function written code , but runs asynchronously until it finishes then it notifies it's callback and in your code the asynchronous method is URLSession.shared.dataTask
which runs in a background thread (that's why you have to insert DispatchQueue.main.async
inside it to refresh the UI ) and leave the serial execution at main thread for sure you can block the main thread until response returns with a method like Data(contentsOf:url)
instead of URLSession.shared.dataTask
but it's not a good idea
thanks for you answer! I'm still not really understanding why that's important. Could you explain!
– teachMeSenpai
Nov 25 '18 at 16:41
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53469529%2farray-thats-supposed-to-store-json-is-empty-after-successful-json-parsing%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You either need
self.pokemons.append(load)
DispatchQueue.main.async {
self.tableView.reloadData()
}
or write a completion
the asynchronous call is something that doesn't go in serial with function written code , but runs asynchronously until it finishes then it notifies it's callback and in your code the asynchronous method is URLSession.shared.dataTask
which runs in a background thread (that's why you have to insert DispatchQueue.main.async
inside it to refresh the UI ) and leave the serial execution at main thread for sure you can block the main thread until response returns with a method like Data(contentsOf:url)
instead of URLSession.shared.dataTask
but it's not a good idea
thanks for you answer! I'm still not really understanding why that's important. Could you explain!
– teachMeSenpai
Nov 25 '18 at 16:41
add a comment |
You either need
self.pokemons.append(load)
DispatchQueue.main.async {
self.tableView.reloadData()
}
or write a completion
the asynchronous call is something that doesn't go in serial with function written code , but runs asynchronously until it finishes then it notifies it's callback and in your code the asynchronous method is URLSession.shared.dataTask
which runs in a background thread (that's why you have to insert DispatchQueue.main.async
inside it to refresh the UI ) and leave the serial execution at main thread for sure you can block the main thread until response returns with a method like Data(contentsOf:url)
instead of URLSession.shared.dataTask
but it's not a good idea
thanks for you answer! I'm still not really understanding why that's important. Could you explain!
– teachMeSenpai
Nov 25 '18 at 16:41
add a comment |
You either need
self.pokemons.append(load)
DispatchQueue.main.async {
self.tableView.reloadData()
}
or write a completion
the asynchronous call is something that doesn't go in serial with function written code , but runs asynchronously until it finishes then it notifies it's callback and in your code the asynchronous method is URLSession.shared.dataTask
which runs in a background thread (that's why you have to insert DispatchQueue.main.async
inside it to refresh the UI ) and leave the serial execution at main thread for sure you can block the main thread until response returns with a method like Data(contentsOf:url)
instead of URLSession.shared.dataTask
but it's not a good idea
You either need
self.pokemons.append(load)
DispatchQueue.main.async {
self.tableView.reloadData()
}
or write a completion
the asynchronous call is something that doesn't go in serial with function written code , but runs asynchronously until it finishes then it notifies it's callback and in your code the asynchronous method is URLSession.shared.dataTask
which runs in a background thread (that's why you have to insert DispatchQueue.main.async
inside it to refresh the UI ) and leave the serial execution at main thread for sure you can block the main thread until response returns with a method like Data(contentsOf:url)
instead of URLSession.shared.dataTask
but it's not a good idea
edited Nov 25 '18 at 20:58
answered Nov 25 '18 at 16:38
Sh_KhanSh_Khan
45.5k51432
45.5k51432
thanks for you answer! I'm still not really understanding why that's important. Could you explain!
– teachMeSenpai
Nov 25 '18 at 16:41
add a comment |
thanks for you answer! I'm still not really understanding why that's important. Could you explain!
– teachMeSenpai
Nov 25 '18 at 16:41
thanks for you answer! I'm still not really understanding why that's important. Could you explain!
– teachMeSenpai
Nov 25 '18 at 16:41
thanks for you answer! I'm still not really understanding why that's important. Could you explain!
– teachMeSenpai
Nov 25 '18 at 16:41
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53469529%2farray-thats-supposed-to-store-json-is-empty-after-successful-json-parsing%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
loadJSON
is asynchronous.– rmaddy
Nov 25 '18 at 16:30
hey! sorry I'm not familiar with what that means. Could you explain more?
– teachMeSenpai
Nov 25 '18 at 16:35