第一步:

创建工程文件

 

第二步:

寻找api,调用网络数据(现在大部分api都是收费的,反正我是找不到了,我这里就做一个示例随便寻找一个旧的api好了)

 

第三步:将网址输入,直接看看访问到的数据;

。。。。。。。。。。。。。。(这什么屌东西,算了咱们不管它,还是能看出字典模式的key,等会儿试试调用)

 

第四步:建造demo,将按钮还有显示信息界面设置好,链接控件,如图:

第五步:写按钮控件的响应事件操作函数WeatherInfo()

  func WeatherInfo(){

       //访问网络

        let url =NSURL(string:"http://www.weather.com.cn/adat/sk/101110101.html")

       let jsonData=NSData(contentsOfURL: url!)

        

//        //方法1 使用NSJSONSerialization解析

//        do {

//            let json=try NSJSONSerialization.JSONObjectWithData(jsonData!, options:[]) as! [String:AnyObject]

//            let weatherInf=json["weatherinfo"] as! NSDictionary

//            let city=weatherInf["city"]!

//            let temp=weatherInf["temp"]!

//            showWeatherInfo.text="城市:\(city)\n温度:\(temp)\n "

//        }catch let error as NSError{

//            print("解析出错。\(error.localizedDescription)")

//        }

        

        //方法2使用SwiftyJSON解析

       let json=JSON(data:jsonData!)

        let city=json["weatherinfo"]["city"]

        let temp=json["weatherinfo"]["temp"]

       showWeatherInfo.text="城市:\(city)\n温度:\(temp)\n"

        

    }

全部代码如下:

 

第七步:运行

 

最后,如果运行程序出现错误提示:
2016-0726 015:06:27.630 Weather[3531:97547] App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
fatal error: unexpectedly found nil while unwrapping an Optional value
原因是 Xcode7禁用了明码的HTTP请求,应该在info.plist里添加字段如下:
打开 工程主目录下info.plist
增加属性字典 App Transport Security Settings
在这个属性下增加节点 Allow Arbitrary Loads, value 为 YES