////Viewcontroller.swift//http_request////Created by Andy on 14-9-6.//Copyright (c) 2014 Andy. All rights reserved.//ImportUIKitclassViewcontroller:uiviewcontroller {@IBOutlet var btn:uibutton?@IBOutlet var Lable:uilabel?override func Viewdidload () {Super. Viewdidload ()//TextField} @IBAction func Btnclick (anyobject) {//SS ()loadjsondata ()}//methods for parsing JSONfunc loadjsondata () {//defines the interface address that gets the JSON data, which is defined as the API interface for getting the weather, and one benefit is that swift statements can be used without forcing the ";" at the end of each statement .var url = nsurl (string: "Http://www.weather.com.cn/data/sk/101110101.html") //Get JSON datavar data =Nsdata.datawithcontentsofurl (Url,options:nsdatareadingoptions.datareadinguncached,error:nil) var json: Anyobject= Nsjsonserialization.jsonobjectwithdata (Data,options:nsjsonreadingoptions.allowfragments,error:nil)!//Parse get JSON field valuevar weatherinfo:anyobject = Json.objectforkey ("Weatherinfo")!//The JSON structure field name. var city:anyobject = Weatherinfo.objectforkey ("City")!//And so on to get the information of the other fields, I don't have to dwell on it. //then assign a corresponding control to the JSON value you acquired. //tv.text = "City: \"//use \ () to embed a variable in the appropriate string .println (city)} func SS () {Let urlpath:string= "Http://www.weather.com.cn/data/sk/101010100.html"var url:nsurl=Nsurl (String:urlpath) var request1:nsurlrequest=nsurlrequest (url:url) let Queue:nsoperationqueue=Nsoperationqueue () nsurlconnection.sendasynchronousrequest (Request1, Queue:queue, Completionh andler:{(Response:nsurlresponse!, data:nsdata!, error:nserror!) -Void in/*Your Code*/var err:nserror var jsonresult:nsdictionary=nsjsonserialization.jsonobjectwithdata (data, Options:NSJSONReadingOptions.MutableContainers, Error:nil) as Nsdictionary println ("Assynchronous\ (Jsonresult)")})} override Func didreceivememorywarning () {Super. didreceivememorywarning ()//Dispose of any resources the can be recreated. }}
iOS Swift HTTP JSON