hatched hatched - 1 year ago 60
Swift Question

How do I store value and display in TableView after succesful HTTP request

I'm using this method to make HTTP request and it successfully return the key and value.

let url = NSURLRequest(URL: NSURL(string: "api.com")!)

let request : NSMutableURLRequest = NSMutableURLRequest()

let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in

if error != nil

let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString)")

do {
if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

There is two keys from the JSON, "title" as String, and "banner" as URL that I need to store as a variable, for displaying in a TableView. How can I store the values? I searched for lots of solution but it doesn't work.

JSON Output


"title":"4G LTE",

Answer Source

I would recommend to store it in a struct. It could be like the following:

struct Promotion {
    let title: String
    let banner: String 

    init(dictionary: [String: AnyObject]) {
        title = dictionary["title"] as? String ?? ""
        banner = dictionary["banner"] as? String ?? ""

As you can see, you can feed a dictionary to it. I can not what happens after convertedJsonIntoDict line, but you can use this struct the following:

// Create a container for storing the promotions
var promotions: [Promotion] = []
// Iterate through every dictionary
for dictionary in convertedJsonIntoDict {
// Create  a promotion
    let promotion = Promotion(dictionary: dictionary as [String : AnyObject])
// Check what do you have in promotions

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download