0

i have the following object class:

class NewsItem: NSObject {

var storyCategory: String?
var titleText: String?
var paragraph1: String?
var paragraph2: String?
var featureImage: String?
var secondImage: String?
var storyDate: String?
var majorReference: String?
var fact: String?
var actualFeatureImage: UIImage? // Using these two to pass the image from home to story view
var actualSecondImage: UIImage?

var referencesArray = [AnyObject]()
...

init?(dictionary: [String: AnyObject]) {

guard

let storyCategory = dictionary["category"] as? String,
let titleText = dictionary["title"] as? String,
let paragraph1 = dictionary["paragraph1"] as? String,
let paragraph2 = dictionary["paragraph2"] as? String,
let featureImage = dictionary["headerImage"] as? String,
let storyDate = dictionary["date"] as? String,
let majorReference = dictionary["majorReference"] as? String,
let secondImage = dictionary["secondImage"] as? String

  else {
  return nil
}

self.storyCategory = storyCategory
self.titleText = titleText
self.paragraph2 = paragraph2
self.paragraph1 = paragraph1
self.featureImage = featureImage
self.storyDate = storyDate
self.majorReference = majorReference
self.fact = dictionary["fact"] as? String //if there's a fact in the dict, it will be assigned and if not there'll be nil
self.secondImage = secondImage

let referenceObject = dictionary["reference"] as? [[String: AnyObject]]
for object in referenceObject! {

    self.referencesArray.append(object)
    //print(object)
}

//bellow is a snippet from the method that's serializing the JSON data

do {
    let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)

    if let newsArticles = json["stories"] as? [[String: AnyObject]] {
      for article in newsArticles {
        let newsArticle = NewsItem(dictionary: article)
        newsItems.append(newsArticle!)

      }
    }
  } catch {
    print("error in the news items delivery: \(error)")
    let displayError = EHPlainAlert(title: "hmmm...", message: "\(error)", type: ViewAlertError)
    displayError.show()
  }

}

in the backend of the app, i have JSON objects and one of the values of each of the objects is as follows:

... "reference" : [
        {
            "refName": "CNN",
            "refURL": "http://edition.cnn.com/2016/07/19/football/brexit-effect-on-english-premier-league/index.html"
        },
        {
            "refName": "Telegraph",  
            "refURL": "http://www.telegraph.co.uk/football/2016/06/21/what-would-brexit-mean-for-the-premier-league/"
        }

    ], ...

i don't know if i have the JSON wrong o' something but what i intend to have is an array of references, each reference having a reference name(refName) and the url of the reference (refURL).

my question is, what would be the best method to have the JSON object above be added to the referencesArray in my object class. Would it be better to use a dictionary instead of an array? if so, how should i re-write my code?

if you need any more details about the code, ask and ye shall receive an update. Thanks!

EDIT

Here's the JSON in full :

{

"stories" : [

    {
    "title" : "English Premier League vs BREXIT: Who will win?",

    "headerImage" : "http://i2.cdn.turner.com/cnnnext/dam/assets/160117112140-rooney-goal-exlarge-169.jpg",

    "category" : "Sports",

    "paragraph1" : "Paragraph text", 

    "paragraph2" : "More text goes here",

    "date" : "21st July",

    "majorReference" : "CNN",

    "reference" : [
        {
            "refName": "CNN",
            "refURL": "http://edition.cnn.com/2016/07/19/football/brexit-effect-on-english-premier-league/index.html"
        },
        {
            "refName": "Telegraph",  
            "refURL": "http://www.telegraph.co.uk/football/2016/06/21/what-would-brexit-mean-for-the-premier-league/"
        }

    ],

    "secondImage"   :   "http://www.telegraph.co.uk/content/dam/football/2016/06/14/02-leicester-afp-xlarge_trans++Wy_u4a9GUNQgLIY2EGV3qvLCN329DeTLuwi-bwi35Bo.jpg",

    "fact" : "Talent will go missing"

    },  ...

Thats just one story... after the comma, is another story.

1
  • Can you post the full JSON? Commented Aug 14, 2016 at 4:49

1 Answer 1

2

First, define a data model for your reference:

struct NewsItemReference {
    var refName: String
    var refURL: NSURL
}

Then modify your NewsItem class as below:

class NewsItem: NSObject {
    var referencesArray = [NewsItemReference]()

    init?(dictionary: [String: AnyObject]) {
        ...
        if let references = dictionary["reference"] as? [[String: AnyObject]] {
            for object in references {
                guard let refName = object["refName"] as? String,
                      let refURLString = object["refURL"] as? String,
                      let refURL = NSURL(string: refURLString) else {
                    continue
                }

                self.referencesArray.append(NewsItemReference(refName: refName, refURL: refURL))
            }
        }
    }

If you see yourself quickly outgrowing this model (the code is too verbose), take a look at some JSON-to-object mapping framework like ObjectMapper.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a ton! You pros always make it look so easy! About the mapper framework, being a beginner in swift, I tried it but couldn't really get it to work. . . if you know any bottom up tutorial links for the implementation of the ObjectMapper lib, please link them here... Again, thank you for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.