iOS swift - working with response from API
I am very new to Swift and iOS development. And I am wondering how to do something relatively simple if I was using JavaScript.
I am making a call to an API that is returning the following. Excuse the formatting but it is directly copied from the Xcode console.
["type": success, "value": <__NSArrayI 0x600000030340>(
{
categories = ();
id = 155;
joke = "Chuck Norris does not "style" his hair. It lays perfectly in place out of sheer terror.";
},
{
categories = (nerdy);
id = 69;
joke = "Scientists have estimated that the energy given off during the Big Bang is roughly equal to 1CNRhK (Chuck Norris Roundhouse Kick).";
}
)
]
I want to loop over the response and add to an array. In JavaScript it would look like the following:
let jokes = ;
response.value.forEach(item => {
jokes.push(item.joke)
})
It doesn't have to be exactly like the above. I am confident using loops in swift and appending to an array. What I am struggling to do is access the jokes in the value
array returned from the API.
My controller looks like the following:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
} catch let error as NSError {
print(error)
}
}).resume()
}
}
ios json swift nsjsonserialization
add a comment |
I am very new to Swift and iOS development. And I am wondering how to do something relatively simple if I was using JavaScript.
I am making a call to an API that is returning the following. Excuse the formatting but it is directly copied from the Xcode console.
["type": success, "value": <__NSArrayI 0x600000030340>(
{
categories = ();
id = 155;
joke = "Chuck Norris does not "style" his hair. It lays perfectly in place out of sheer terror.";
},
{
categories = (nerdy);
id = 69;
joke = "Scientists have estimated that the energy given off during the Big Bang is roughly equal to 1CNRhK (Chuck Norris Roundhouse Kick).";
}
)
]
I want to loop over the response and add to an array. In JavaScript it would look like the following:
let jokes = ;
response.value.forEach(item => {
jokes.push(item.joke)
})
It doesn't have to be exactly like the above. I am confident using loops in swift and appending to an array. What I am struggling to do is access the jokes in the value
array returned from the API.
My controller looks like the following:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
} catch let error as NSError {
print(error)
}
}).resume()
}
}
ios json swift nsjsonserialization
The reason this is easy in JS and that there's additional work in in Swift is because you're on the border between typed and untyped behavior. JS & JSON - untyped. Swift would like to add some typing when reading the JSON;Any
isn't all that useful without casting. There are several frameworks out there to help (e.g. SwiftyJSON) and Swift itself has added Codable/Decodable.
– Graham Perks
Nov 22 '18 at 14:33
great, this is all brilliant to know @GrahamPerks. Just a question - lets say a production web React based app will be potentially making lots of API calls and storing this data in a redux store. Is there some similar approach with iOS development or is there something else I should be aware of?
– peter flanagan
Nov 22 '18 at 14:44
That's a whole other question... I usually take one of 2 approaches. Parse & insert the downloaded data into SQLite, if I need it persistent. Or store it in RAM more like redux, e.g. with a singleton JokeManager class which can parse a JSON-derived dict[String:Any]
into some useful Swift objects. Then the UI or whatever can pull jokes fromJokeManager.shared
as needed.
– Graham Perks
Nov 22 '18 at 14:50
it sure is another question, but thanks for answering. Gives me something to research :-D -- but what you suggested is the method used for production apps?
– peter flanagan
Nov 22 '18 at 14:58
SwiftyJSON looks great by the way
– peter flanagan
Nov 22 '18 at 15:22
add a comment |
I am very new to Swift and iOS development. And I am wondering how to do something relatively simple if I was using JavaScript.
I am making a call to an API that is returning the following. Excuse the formatting but it is directly copied from the Xcode console.
["type": success, "value": <__NSArrayI 0x600000030340>(
{
categories = ();
id = 155;
joke = "Chuck Norris does not "style" his hair. It lays perfectly in place out of sheer terror.";
},
{
categories = (nerdy);
id = 69;
joke = "Scientists have estimated that the energy given off during the Big Bang is roughly equal to 1CNRhK (Chuck Norris Roundhouse Kick).";
}
)
]
I want to loop over the response and add to an array. In JavaScript it would look like the following:
let jokes = ;
response.value.forEach(item => {
jokes.push(item.joke)
})
It doesn't have to be exactly like the above. I am confident using loops in swift and appending to an array. What I am struggling to do is access the jokes in the value
array returned from the API.
My controller looks like the following:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
} catch let error as NSError {
print(error)
}
}).resume()
}
}
ios json swift nsjsonserialization
I am very new to Swift and iOS development. And I am wondering how to do something relatively simple if I was using JavaScript.
I am making a call to an API that is returning the following. Excuse the formatting but it is directly copied from the Xcode console.
["type": success, "value": <__NSArrayI 0x600000030340>(
{
categories = ();
id = 155;
joke = "Chuck Norris does not "style" his hair. It lays perfectly in place out of sheer terror.";
},
{
categories = (nerdy);
id = 69;
joke = "Scientists have estimated that the energy given off during the Big Bang is roughly equal to 1CNRhK (Chuck Norris Roundhouse Kick).";
}
)
]
I want to loop over the response and add to an array. In JavaScript it would look like the following:
let jokes = ;
response.value.forEach(item => {
jokes.push(item.joke)
})
It doesn't have to be exactly like the above. I am confident using loops in swift and appending to an array. What I am struggling to do is access the jokes in the value
array returned from the API.
My controller looks like the following:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
} catch let error as NSError {
print(error)
}
}).resume()
}
}
ios json swift nsjsonserialization
ios json swift nsjsonserialization
edited Nov 22 '18 at 14:32
peter flanagan
asked Nov 22 '18 at 14:02
peter flanaganpeter flanagan
80811133
80811133
The reason this is easy in JS and that there's additional work in in Swift is because you're on the border between typed and untyped behavior. JS & JSON - untyped. Swift would like to add some typing when reading the JSON;Any
isn't all that useful without casting. There are several frameworks out there to help (e.g. SwiftyJSON) and Swift itself has added Codable/Decodable.
– Graham Perks
Nov 22 '18 at 14:33
great, this is all brilliant to know @GrahamPerks. Just a question - lets say a production web React based app will be potentially making lots of API calls and storing this data in a redux store. Is there some similar approach with iOS development or is there something else I should be aware of?
– peter flanagan
Nov 22 '18 at 14:44
That's a whole other question... I usually take one of 2 approaches. Parse & insert the downloaded data into SQLite, if I need it persistent. Or store it in RAM more like redux, e.g. with a singleton JokeManager class which can parse a JSON-derived dict[String:Any]
into some useful Swift objects. Then the UI or whatever can pull jokes fromJokeManager.shared
as needed.
– Graham Perks
Nov 22 '18 at 14:50
it sure is another question, but thanks for answering. Gives me something to research :-D -- but what you suggested is the method used for production apps?
– peter flanagan
Nov 22 '18 at 14:58
SwiftyJSON looks great by the way
– peter flanagan
Nov 22 '18 at 15:22
add a comment |
The reason this is easy in JS and that there's additional work in in Swift is because you're on the border between typed and untyped behavior. JS & JSON - untyped. Swift would like to add some typing when reading the JSON;Any
isn't all that useful without casting. There are several frameworks out there to help (e.g. SwiftyJSON) and Swift itself has added Codable/Decodable.
– Graham Perks
Nov 22 '18 at 14:33
great, this is all brilliant to know @GrahamPerks. Just a question - lets say a production web React based app will be potentially making lots of API calls and storing this data in a redux store. Is there some similar approach with iOS development or is there something else I should be aware of?
– peter flanagan
Nov 22 '18 at 14:44
That's a whole other question... I usually take one of 2 approaches. Parse & insert the downloaded data into SQLite, if I need it persistent. Or store it in RAM more like redux, e.g. with a singleton JokeManager class which can parse a JSON-derived dict[String:Any]
into some useful Swift objects. Then the UI or whatever can pull jokes fromJokeManager.shared
as needed.
– Graham Perks
Nov 22 '18 at 14:50
it sure is another question, but thanks for answering. Gives me something to research :-D -- but what you suggested is the method used for production apps?
– peter flanagan
Nov 22 '18 at 14:58
SwiftyJSON looks great by the way
– peter flanagan
Nov 22 '18 at 15:22
The reason this is easy in JS and that there's additional work in in Swift is because you're on the border between typed and untyped behavior. JS & JSON - untyped. Swift would like to add some typing when reading the JSON;
Any
isn't all that useful without casting. There are several frameworks out there to help (e.g. SwiftyJSON) and Swift itself has added Codable/Decodable.– Graham Perks
Nov 22 '18 at 14:33
The reason this is easy in JS and that there's additional work in in Swift is because you're on the border between typed and untyped behavior. JS & JSON - untyped. Swift would like to add some typing when reading the JSON;
Any
isn't all that useful without casting. There are several frameworks out there to help (e.g. SwiftyJSON) and Swift itself has added Codable/Decodable.– Graham Perks
Nov 22 '18 at 14:33
great, this is all brilliant to know @GrahamPerks. Just a question - lets say a production web React based app will be potentially making lots of API calls and storing this data in a redux store. Is there some similar approach with iOS development or is there something else I should be aware of?
– peter flanagan
Nov 22 '18 at 14:44
great, this is all brilliant to know @GrahamPerks. Just a question - lets say a production web React based app will be potentially making lots of API calls and storing this data in a redux store. Is there some similar approach with iOS development or is there something else I should be aware of?
– peter flanagan
Nov 22 '18 at 14:44
That's a whole other question... I usually take one of 2 approaches. Parse & insert the downloaded data into SQLite, if I need it persistent. Or store it in RAM more like redux, e.g. with a singleton JokeManager class which can parse a JSON-derived dict
[String:Any]
into some useful Swift objects. Then the UI or whatever can pull jokes from JokeManager.shared
as needed.– Graham Perks
Nov 22 '18 at 14:50
That's a whole other question... I usually take one of 2 approaches. Parse & insert the downloaded data into SQLite, if I need it persistent. Or store it in RAM more like redux, e.g. with a singleton JokeManager class which can parse a JSON-derived dict
[String:Any]
into some useful Swift objects. Then the UI or whatever can pull jokes from JokeManager.shared
as needed.– Graham Perks
Nov 22 '18 at 14:50
it sure is another question, but thanks for answering. Gives me something to research :-D -- but what you suggested is the method used for production apps?
– peter flanagan
Nov 22 '18 at 14:58
it sure is another question, but thanks for answering. Gives me something to research :-D -- but what you suggested is the method used for production apps?
– peter flanagan
Nov 22 '18 at 14:58
SwiftyJSON looks great by the way
– peter flanagan
Nov 22 '18 at 15:22
SwiftyJSON looks great by the way
– peter flanagan
Nov 22 '18 at 15:22
add a comment |
2 Answers
2
active
oldest
votes
You can try
if let va = json["value"] as? [[String:Any]] {
va.forEach { print($0["joke"]) }
}
I would prefer to write a Codable
structs for this
struct Root: Codable {
let type: String
let value: [Value]
}
struct Value: Codable {
let categories: [Category]
let id: Int
let joke: String
}
struct Category: Codable {
}
let res = try? JSONDecoder().decode(Root.self,from:data)
print(res.value)
1
That works thanks. Is this not a very common task in iOS/swift? as in web development it is. Is there a different approach to fetching data used in mobile applications that I am unaware of? Also, would you mind showing me how you would take thestruct
approach?
– peter flanagan
Nov 22 '18 at 14:07
add a comment |
As you can see from logs the variable json["value"] is of type NSArray so you can do something like this to get your data (there are so many ways to do that).
First of all you can create the object Joke you wanna take like this
class Joke: NSObject {
var categories = [String]()
var id: Int?
var joke: String?
init(json: [String: Any]) {
if let categories = json["categories"] as? String {
for category in categories {
self.categories.append(category)
}
}
if let id = json["id"] as? Int {
self.id = id
}
if let joke = json[""] as? String {
self.joke = joke
}
}
}
And then you do this in your ViewController
class ViewController: UIViewController {
var jokes = [Joke]()
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
let arrayOfObject = json["value"] as! NSArray
for object in arrayOfObject {
if let json = object as? [String: Any] {
let object = Joke(json: json)
// Now you have your object containing the data from the JSON and you can insert it in your array of Object
jokes.append(object)
}
}
} catch let error as NSError {
print(error)
}
}).resume()
}
}
Remember, there are so many ways to do that, I showed you a simply way to do it, hope it will be helpful.
thanks, gave you an upvote
– peter flanagan
Nov 22 '18 at 14:37
Thank you very much :)
– Francesco Destino
Nov 22 '18 at 14:40
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%2f53432664%2fios-swift-working-with-response-from-api%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can try
if let va = json["value"] as? [[String:Any]] {
va.forEach { print($0["joke"]) }
}
I would prefer to write a Codable
structs for this
struct Root: Codable {
let type: String
let value: [Value]
}
struct Value: Codable {
let categories: [Category]
let id: Int
let joke: String
}
struct Category: Codable {
}
let res = try? JSONDecoder().decode(Root.self,from:data)
print(res.value)
1
That works thanks. Is this not a very common task in iOS/swift? as in web development it is. Is there a different approach to fetching data used in mobile applications that I am unaware of? Also, would you mind showing me how you would take thestruct
approach?
– peter flanagan
Nov 22 '18 at 14:07
add a comment |
You can try
if let va = json["value"] as? [[String:Any]] {
va.forEach { print($0["joke"]) }
}
I would prefer to write a Codable
structs for this
struct Root: Codable {
let type: String
let value: [Value]
}
struct Value: Codable {
let categories: [Category]
let id: Int
let joke: String
}
struct Category: Codable {
}
let res = try? JSONDecoder().decode(Root.self,from:data)
print(res.value)
1
That works thanks. Is this not a very common task in iOS/swift? as in web development it is. Is there a different approach to fetching data used in mobile applications that I am unaware of? Also, would you mind showing me how you would take thestruct
approach?
– peter flanagan
Nov 22 '18 at 14:07
add a comment |
You can try
if let va = json["value"] as? [[String:Any]] {
va.forEach { print($0["joke"]) }
}
I would prefer to write a Codable
structs for this
struct Root: Codable {
let type: String
let value: [Value]
}
struct Value: Codable {
let categories: [Category]
let id: Int
let joke: String
}
struct Category: Codable {
}
let res = try? JSONDecoder().decode(Root.self,from:data)
print(res.value)
You can try
if let va = json["value"] as? [[String:Any]] {
va.forEach { print($0["joke"]) }
}
I would prefer to write a Codable
structs for this
struct Root: Codable {
let type: String
let value: [Value]
}
struct Value: Codable {
let categories: [Category]
let id: Int
let joke: String
}
struct Category: Codable {
}
let res = try? JSONDecoder().decode(Root.self,from:data)
print(res.value)
edited Nov 22 '18 at 14:29
answered Nov 22 '18 at 14:06
Sh_KhanSh_Khan
41.3k51125
41.3k51125
1
That works thanks. Is this not a very common task in iOS/swift? as in web development it is. Is there a different approach to fetching data used in mobile applications that I am unaware of? Also, would you mind showing me how you would take thestruct
approach?
– peter flanagan
Nov 22 '18 at 14:07
add a comment |
1
That works thanks. Is this not a very common task in iOS/swift? as in web development it is. Is there a different approach to fetching data used in mobile applications that I am unaware of? Also, would you mind showing me how you would take thestruct
approach?
– peter flanagan
Nov 22 '18 at 14:07
1
1
That works thanks. Is this not a very common task in iOS/swift? as in web development it is. Is there a different approach to fetching data used in mobile applications that I am unaware of? Also, would you mind showing me how you would take the
struct
approach?– peter flanagan
Nov 22 '18 at 14:07
That works thanks. Is this not a very common task in iOS/swift? as in web development it is. Is there a different approach to fetching data used in mobile applications that I am unaware of? Also, would you mind showing me how you would take the
struct
approach?– peter flanagan
Nov 22 '18 at 14:07
add a comment |
As you can see from logs the variable json["value"] is of type NSArray so you can do something like this to get your data (there are so many ways to do that).
First of all you can create the object Joke you wanna take like this
class Joke: NSObject {
var categories = [String]()
var id: Int?
var joke: String?
init(json: [String: Any]) {
if let categories = json["categories"] as? String {
for category in categories {
self.categories.append(category)
}
}
if let id = json["id"] as? Int {
self.id = id
}
if let joke = json[""] as? String {
self.joke = joke
}
}
}
And then you do this in your ViewController
class ViewController: UIViewController {
var jokes = [Joke]()
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
let arrayOfObject = json["value"] as! NSArray
for object in arrayOfObject {
if let json = object as? [String: Any] {
let object = Joke(json: json)
// Now you have your object containing the data from the JSON and you can insert it in your array of Object
jokes.append(object)
}
}
} catch let error as NSError {
print(error)
}
}).resume()
}
}
Remember, there are so many ways to do that, I showed you a simply way to do it, hope it will be helpful.
thanks, gave you an upvote
– peter flanagan
Nov 22 '18 at 14:37
Thank you very much :)
– Francesco Destino
Nov 22 '18 at 14:40
add a comment |
As you can see from logs the variable json["value"] is of type NSArray so you can do something like this to get your data (there are so many ways to do that).
First of all you can create the object Joke you wanna take like this
class Joke: NSObject {
var categories = [String]()
var id: Int?
var joke: String?
init(json: [String: Any]) {
if let categories = json["categories"] as? String {
for category in categories {
self.categories.append(category)
}
}
if let id = json["id"] as? Int {
self.id = id
}
if let joke = json[""] as? String {
self.joke = joke
}
}
}
And then you do this in your ViewController
class ViewController: UIViewController {
var jokes = [Joke]()
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
let arrayOfObject = json["value"] as! NSArray
for object in arrayOfObject {
if let json = object as? [String: Any] {
let object = Joke(json: json)
// Now you have your object containing the data from the JSON and you can insert it in your array of Object
jokes.append(object)
}
}
} catch let error as NSError {
print(error)
}
}).resume()
}
}
Remember, there are so many ways to do that, I showed you a simply way to do it, hope it will be helpful.
thanks, gave you an upvote
– peter flanagan
Nov 22 '18 at 14:37
Thank you very much :)
– Francesco Destino
Nov 22 '18 at 14:40
add a comment |
As you can see from logs the variable json["value"] is of type NSArray so you can do something like this to get your data (there are so many ways to do that).
First of all you can create the object Joke you wanna take like this
class Joke: NSObject {
var categories = [String]()
var id: Int?
var joke: String?
init(json: [String: Any]) {
if let categories = json["categories"] as? String {
for category in categories {
self.categories.append(category)
}
}
if let id = json["id"] as? Int {
self.id = id
}
if let joke = json[""] as? String {
self.joke = joke
}
}
}
And then you do this in your ViewController
class ViewController: UIViewController {
var jokes = [Joke]()
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
let arrayOfObject = json["value"] as! NSArray
for object in arrayOfObject {
if let json = object as? [String: Any] {
let object = Joke(json: json)
// Now you have your object containing the data from the JSON and you can insert it in your array of Object
jokes.append(object)
}
}
} catch let error as NSError {
print(error)
}
}).resume()
}
}
Remember, there are so many ways to do that, I showed you a simply way to do it, hope it will be helpful.
As you can see from logs the variable json["value"] is of type NSArray so you can do something like this to get your data (there are so many ways to do that).
First of all you can create the object Joke you wanna take like this
class Joke: NSObject {
var categories = [String]()
var id: Int?
var joke: String?
init(json: [String: Any]) {
if let categories = json["categories"] as? String {
for category in categories {
self.categories.append(category)
}
}
if let id = json["id"] as? Int {
self.id = id
}
if let joke = json[""] as? String {
self.joke = joke
}
}
}
And then you do this in your ViewController
class ViewController: UIViewController {
var jokes = [Joke]()
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.icndb.com/jokes/random/2")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print(json["value"])
// not sure how to access each joke in the array here
let arrayOfObject = json["value"] as! NSArray
for object in arrayOfObject {
if let json = object as? [String: Any] {
let object = Joke(json: json)
// Now you have your object containing the data from the JSON and you can insert it in your array of Object
jokes.append(object)
}
}
} catch let error as NSError {
print(error)
}
}).resume()
}
}
Remember, there are so many ways to do that, I showed you a simply way to do it, hope it will be helpful.
edited Nov 22 '18 at 14:37
answered Nov 22 '18 at 14:36
Francesco DestinoFrancesco Destino
24111
24111
thanks, gave you an upvote
– peter flanagan
Nov 22 '18 at 14:37
Thank you very much :)
– Francesco Destino
Nov 22 '18 at 14:40
add a comment |
thanks, gave you an upvote
– peter flanagan
Nov 22 '18 at 14:37
Thank you very much :)
– Francesco Destino
Nov 22 '18 at 14:40
thanks, gave you an upvote
– peter flanagan
Nov 22 '18 at 14:37
thanks, gave you an upvote
– peter flanagan
Nov 22 '18 at 14:37
Thank you very much :)
– Francesco Destino
Nov 22 '18 at 14:40
Thank you very much :)
– Francesco Destino
Nov 22 '18 at 14:40
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%2f53432664%2fios-swift-working-with-response-from-api%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
The reason this is easy in JS and that there's additional work in in Swift is because you're on the border between typed and untyped behavior. JS & JSON - untyped. Swift would like to add some typing when reading the JSON;
Any
isn't all that useful without casting. There are several frameworks out there to help (e.g. SwiftyJSON) and Swift itself has added Codable/Decodable.– Graham Perks
Nov 22 '18 at 14:33
great, this is all brilliant to know @GrahamPerks. Just a question - lets say a production web React based app will be potentially making lots of API calls and storing this data in a redux store. Is there some similar approach with iOS development or is there something else I should be aware of?
– peter flanagan
Nov 22 '18 at 14:44
That's a whole other question... I usually take one of 2 approaches. Parse & insert the downloaded data into SQLite, if I need it persistent. Or store it in RAM more like redux, e.g. with a singleton JokeManager class which can parse a JSON-derived dict
[String:Any]
into some useful Swift objects. Then the UI or whatever can pull jokes fromJokeManager.shared
as needed.– Graham Perks
Nov 22 '18 at 14:50
it sure is another question, but thanks for answering. Gives me something to research :-D -- but what you suggested is the method used for production apps?
– peter flanagan
Nov 22 '18 at 14:58
SwiftyJSON looks great by the way
– peter flanagan
Nov 22 '18 at 15:22