Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ViewController.swift
- // json
- //
- // Created by admin on 18.02.16.
- // Copyright © 2016 admin. All rights reserved.
- //
- import UIKit
- class ViewController: UIViewController {
- //GLOBAL VARIABLES
- var globalJsonLink = "http://www.learnswiftonline.com/Samples/subway.json"
- //OUTLETS
- @IBOutlet weak var statusLabel: UILabel!
- @IBOutlet weak var localhostSwitch: UISwitch!
- //ACTIONS
- @IBAction func jsonButton(sender: UIButton) {
- callSubwayJson()
- // callRandomPersonJson()
- }
- @IBAction func localhostSwitched(sender: AnyObject) {
- if localhostSwitch.on
- {
- globalJsonLink = "http://localhost/bonus/api/long.json"
- }
- else
- {
- globalJsonLink = "http://www.learnswiftonline.com/Samples/subway.json"
- }
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do any additional setup after loading the view, typically from a nib.
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- // SUBWAY JSON
- func callSubwayJson(){
- //CHANGE requestURL value depending on the localhostSwitch.on state
- let requestURL: NSURL = (NSURL(string: globalJsonLink))!
- let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
- let session = NSURLSession.sharedSession()
- let task = session.dataTaskWithRequest(urlRequest) {
- (data, response, error) -> Void in
- let httpResponse = response as! NSHTTPURLResponse
- let statusCode = httpResponse.statusCode
- if (statusCode == 200) {
- do{
- let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
- if let stations = json["stations"] as? [[String: AnyObject]] {
- for station in stations {
- if let name = station["stationName"] as? String {
- if let year = station["buildYear"] as? String {
- NSLog("%@ (Built %@)",name,year)
- }
- }
- }
- }
- }catch {
- print("Error with Json: \(error)")
- }
- }
- }
- task.resume()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement