Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ViewController.swift
- // MyJson
- //
- // Created by HackerU on 24/04/2017.
- // Copyright © 2017 HackerU. All rights reserved.
- //
- import UIKit
- class ViewController: UIViewController {
- let s=URLSession.shared
- override func viewDidLoad() {
- // json1()
- //json2()
- json3() //for Elinor
- }
- //example 1 - simple read
- func json1()
- {
- let url=URL(string: "http://nikita.hackeruweb.co.il/hackSwift/mini.json")!
- s.dataTask(with:url, completionHandler:{(d,r,e)in
- //get the information as raw data into json variable
- let json = try! JSONSerialization.jsonObject(with: d!, options: .mutableContainers) as! [String:Any];
- print (json)
- }).resume()
- }
- //example 2 - parse the data
- func json2()
- {
- let url=URL(string: "http://nikita.hackeruweb.co.il/hackSwift/mini.json")!
- s.dataTask(with: url, completionHandler: {(d,r,e)in
- //get the raw information from our json data
- let json = try! JSONSerialization.jsonObject(with: d!, options: .mutableContainers) as! [String:Any];
- print("\(json["name"]!) is \(json["age"]!) years old")
- print("and he knows the following languages:")
- for singleLang in json["langs"] as! [String] //print all the languages
- {
- print(singleLang)
- }
- }).resume()
- }
- //example 3 - complexed json
- func json3()
- {
- let url=URL(string: "http://nikita.hackeruweb.co.il/hackDroid/items.json")!
- s.dataTask(with: url, completionHandler: {(d,r,e)in
- if let json = try? JSONSerialization.jsonObject(with: d!, options: .mutableContainers) as! [String:Any]
- {
- let hits = json["hits"] as! [Any] //get array hits from json
- for hitSingle in hits {//iterate over all "hits"
- let source = (hitSingle as! [String:Any])["_source"]! //get "_source" from each hit
- let info=(source as! [String:Any])["info"]!
- if let icon=(info as! [String:Any])["icon"]
- {
- print (icon)
- }
- else
- {
- print ("No bladdy icon")
- }
- }
- }
- }).resume()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement