swift http请求返回json数据并解析

1 AppDelegate.swift

//
//  AppDelegate.swift
//  QQDemo
//
//  Created by 赵超 on 14-6-21.
//  Copyright (c) 2014年 赵超. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // Override point for customization after application launch.
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()

        var root=RootViewController()
        self.window!.rootViewController=root

        return true
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}

2.rootViewController.swift

//
//  RootViewController.swift
//  QQDemo
//
//  Created by 赵超 on 14-6-21.
//  Copyright (c) 2014年 赵超. All rights reserved.
//

import UIKit

class RootViewController: UIViewController {

    var btn:UIButton?
    var text:UITextField?
    var lable:UILabel?

    override func viewDidLoad() {
        super.viewDidLoad()
        //TextField
        text=UITextField()
        text!.frame=CGRectMake(20,30,self.view.bounds.size.width-40,30)
        text!.placeholder="http://"
        text!.borderStyle = .RoundedRect

        //Button
        btn=UIButton()
        btn!.frame=CGRectMake(20, 80, 60, 30)
        btn!.setTitle("HTTP",forState:.Normal)
        btn!.addTarget(self,action:"onclick",forControlEvents:.TouchUpInside)
        btn!.backgroundColor=UIColor.redColor()

        //Lable
        lable=UILabel()
        lable!.frame=CGRectMake(0,120,self.view.bounds.size.width,self.view.bounds.size.height)
        lable!.backgroundColor=UIColor.grayColor()
        lable!.lineBreakMode = .ByWordWrapping;
        lable!.numberOfLines=0

        self.view.addSubview(self.btn)
        self.view.addSubview(lable)
        self.view.addSubview(text)

        // Do any additional setup after loading the view.
    }

    func connection(connection:NSURLConnection!,didReceiveData data:NSData!){
        var returnString:NSString?
        returnString=NSString(data:data,encoding:NSUTF8StringEncoding)
        println(returnString)
        let jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
        var str="result:\n"+String(returnString!)

        for (key,value) in jsonData{
            str+="\n key-->\(key)"+" value=\(value) "
        }
        lable!.text=str

    }

    func onclick(){
        var url:String=text!.text
        if url==""  {
//            let alert=UIAlertView()
//            alert.title="Error"
//            alert.message="please enter url!"
//            alert.addButtonWithTitle("Ok")
//            alert.show()
            var urlString:String?="http://192.168.1.104:8080/Attendace/JsonController/getJson"
            httpRequest(urlString!)

        }else{
            httpRequest(url)
        }

    }
    func httpRequest( urlString:String){
        var url:NSURL?
        var requrst:NSURLRequest?
        var conn:NSURLConnection?
        url=NSURL.URLWithString(urlString)
        requrst=NSURLRequest(URL:url)
        conn=NSURLConnection(request: requrst,delegate: self)
        println(conn)
        if(conn){
            println("http连接成功!")
        }else{
            println("http连接失败!")
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

swift http请求返回json数据并解析,布布扣,bubuko.com

时间: 2024-10-19 21:14:32

swift http请求返回json数据并解析的相关文章

swift http请求返回json数据和分析

1 AppDelegate.swift // // AppDelegate.swift // QQDemo // // Created by 赵超 on 14-6-21. // Copyright (c) 2014年 赵超. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? fun

android通过httpClient请求获取JSON数据并且解析

android通过httpClient请求获取JSON数据并且解析:http://www.cnblogs.com/gzggyy/archive/2013/05/08/3066288.html Android--使用Http向服务器发送请求并取得返回结果,下载图片:http://www.2cto.com/kf/201307/229489.html Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据):http://blog.csdn.net/he

Java从网络中请求获取JSon数据以及解析JSON数据----(自创,请注明)

Json数据是比较常用的数据类型解析,优点就不多说啦.来看看方法: public static JSONObject getJsonObject(String url) { JSONObject jsonObject = null; try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpParams httpParams = httpClient.getPara

Ajax请求返回Json数据

介绍一下用Ajax向服务器请求数据的方法,以及对于返回的Json数据的使用. 1 $.ajax({ 2 type:"post", 3 async:false, 4 url: ******** 5 data:{"province":$("#provice").val(), 6 "city":$("#city").val(), 7 "area":$("#area").va

android 客户端访问自己建立的服务器并返回JSON数据进行解析学习

最近在找关于客户端访问服务器开发的用例 总是去访问别人的网站也不能对里面的数据进行修改也不知道是怎么实现的,自己在网上申请了一个免费的服务器网站上传了一个php文件,现在就可以通过urlStr===http://1.hellowes.sinaapp.com/访问服务器上的信息了,并且服务器会返回一个数据,由于对php一点不懂所以服务器上返回的并不是真正的JSON数据,所以只好通过客户端字符串组合成一个JSON语句通过JSONObject进行解析出来, 下面贴出实现代码,总算是可以从服务器上获取信

php的curl获取https加密协议请求返回json数据进行信息获取

欢迎增加php架构师之旅 群:410028331(招纳贤人-大师中)方便技术的交流 <?php header("Content-type:text/html; charset=utf-8"); function getToken($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //相当关键,这句话是让curl_exec

ajax https请求返回json数据

怎么获取通过ajax请求的html代码:http://zhidao.baidu.com/link?url=Vk7mfepx1tNOp6DAy7KYY_wcUlKQxwwGpmCmct3akDwyXt5P8IIbzY_bLqABCUDFHFtbZs90jmYG11iN5APMKR-T7Acvix9A_DDcOpJA9lu http://www.iteye.com/problems/84999

Android 网络请求json数据,解析json数据,生成对应的java bean类一步到位,快速开发

Android 网络请求一般都涉及到图片和JSON数据,怎样快速的请求网络JSON数据,解析JSON数据,并且一步生成自己想要的Java bean实体类?这个涉及到Android 开发效率的问题.由于接触Android 网络这方面比较多,自然就找到一些好的方法来快速开发Android 网络模块的相关内容,接下来就为大家揭晓 一步快速请求,解析JSON 数据生成对应的Java bean实体类的方法. 注:我们先把思路讲解下吧: 1.网络请求JSON数据代码可以自己写,当然我还是推荐使用网络上开源的

jQuery通过Ajax向PHP服务端发送请求并返回JSON数据

ON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写,同时也易于机器解析和生成.JSON在前后台交互的过程中发挥着相当出色的作用.请接着往下看教程. XHTML  <ul id="userlist">    <li><a href="#" rel="1">张三</a></li>    <li><a href=&quo