2

I'm new in swift language, newbie question but I have to ask cause my mind is little bit confused about dictionary and array usage here, I got a json like this;

 {
  "MainPageLast": [
  {},
  {}..
  ],
  "MainPageSport": [
  {},
  {}..
  ],
  "MainPageEco": [
  {},
  {}..
  ],
  "MainPagePol": [
  {},
  {}..
  ]
}

I made base class which includes all of these arrays as dictionary like this;

public class func modelsFromDictionaryArray(array:NSArray) -> [Json4Swift_Base]
    {
        var models:[Json4Swift_Base] = []
        for item in array
        {
            models.append(Json4Swift_Base(dictionary: item as! NSDictionary)!)
        }
        return models
    }

required public init?(dictionary: NSDictionary) {

        if (dictionary["MainPageLast"] != nil) { mainPageLast = MainPageLast.modelsFromDictionaryArray(dictionary["MainPageLast"] as! NSArray) }
        if (dictionary["MainPageSport"] != nil) { mainPageSport = MainPageSport.modelsFromDictionaryArray(dictionary["MainPageSport"] as! NSArray) }
        if (dictionary["MainPageEco"] != nil) { mainPageEco = MainPageEco.modelsFromDictionaryArray(dictionary["MainPageEco"] as! NSArray) }
        if (dictionary["MainPagePol"] != nil) { mainPagePol = MainPagePol.modelsFromDictionaryArray(dictionary["MainPagePol"] as! NSArray) }
    }

public func dictionaryRepresentation() -> NSDictionary {

        let dictionary = NSMutableDictionary()


        return dictionary
    }

And I try to get data and try to parse and want to see the returning data in debug screen;

func loadHeadline(completion : ((AnyObject) -> Void)!) {

        let urlString = "http://myapiurl."

        let session = NSURLSession.sharedSession()
        let newsUrl = NSURL(string: urlString)

        let task = session.dataTaskWithURL(newsUrl!, completionHandler: {
            (data, response, error) -> Void in

            do {
                let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! Dictionary<String, AnyObject>

                var models:[Json4Swift_Base] = []
                for item in jsonData
                {
                    models.append(Json4Swift_Base(dictionary: item as NSDictionary)!)
                }

            } catch let error as NSError{
                print("Failed to load: \(error.localizedDescription)")
            }

        })
        task.resume()
    }

I know I need to reach each [0], [1]... items one by one in Json4Swift_Base class but I really could not figure how to.

This Exception throws when I try to

models.append

exc_bad_instruction (code=exc_i386_invop subcode=0x0)

Now, which way should I follow or what to do to get and put all data in one.

Thanks in advice..

6
  • do you have a sample dataset of the json you would handle? I can try it in a playground Commented Aug 8, 2016 at 10:26
  • @Scriptable can you check the first code block please. Do you need more info about it ? Thanks. Commented Aug 8, 2016 at 10:27
  • it would be handy to know what is in the array too i think Commented Aug 8, 2016 at 10:28
  • 1
    Since you are new to Swift, get used to the native collection types Array and Dictionary which suit the strong type system of Swift much more than the Foundation equivalents. Commented Aug 8, 2016 at 10:36
  • @vadian thanks for the advice but I need to figure out how to handle that.. Commented Aug 8, 2016 at 11:33

1 Answer 1

2
let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
                do {
                    let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSArray

                    if let allData = jsonResult[0] as? NSDictionary {
                        let header = allData.objectForKey("MainPageMansetData")
                        let magazine = allData.objectForKey("MainPageMagazineData")
                        let sports = allData.objectForKey("MainPageSportsData")
                        let articles = allData.objectForKey("MainPageOtherArticles")

                        print("\(header) \n \(magazine) \n \(sports) \n \(articles)")
                    }
                } catch {}
Sign up to request clarification or add additional context in comments.

1 Comment

Can you check the updated code block. In Json4Swift_Base, there is also code block like that at the end. So it is dictionary. I tried your answer also and xcode says; "cannot covert value type anyobject to nsdictionary in coercion.."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.