Pr Dan Pr Dan - 3 months ago 7
Swift Question

why are my items not going into the array? Xcode and swift NSURLSession

I am using Swift and Xcode, I have built model object with the following variables:

var itemImageNames: [String]?
var itemTitle: String?
var itemDescription: String?
var itemURL: String?


In the mainviewcontroller, I created an variable of model type. I am initiating a NSURLSession...dataTaskWithURL... and adding itemImageNames that I receive back from the server by using append. The data comes back as valid, I've parsed it and it is indeed coming back as Strings. I've tried two solutions,


  1. create a string array out of the images and set that array to self.item.itemImageNames?

    do {
    if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String: AnyObject]] {

    var imageURLs: [String] = [""]

    for dictionary in json {
    if let imageURL = dictionary["url"] as? String {
    imageURLs.append(imageURL)
    print(imageURL)
    }
    }

    self.featuredItem.itemImageNames? = imageURLs

  2. append each of the strings as I get them using self.item.itemImageNames?.append(image)

    do {
    if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String: AnyObject]] {

    for dictionary in json {
    if let imageURL = dictionary["url"] as? String {
    self.featuredItem.itemImageNames?.append(imageURL)
    print(imageURL)
    }
    }



For some reason, the itemImageNames remains nil, using both approaches. I am sure it will work if I just use one image (e.g. the 1st image), and change itemImageNames to a "String?".

In addition, I can update the itemTitle, itemDescription, and itemURL easily by just setting them to self.item.itemTitle, self.item.itemDescription, self.item.itemURL, respectively. Is there something I'm missing on how to enter information into an array?

Answer

In approach #2 initialize the itemImageNames array before trying to append to it. If you try to append to an array that is nil then nothing will happen.

itemImageNames = []

for dictionary in json {
    if let imageURL = dictionary["url"] as? String {
        self.featuredItem.itemImageNames?.append(imageURL)
        print(imageURL)
    }
}