码迷,mamicode.com
首页 > 编程语言 > 详细

Swift基础知识整理

时间:2014-12-22 12:47:56      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

定义一个数组:

var a:[String]=["File", "Edit", "View", "Navigate"]

定义一个字典:

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

定义一个NSMutableDictionary数组

var a:[String]=["File", "Edit", "View", "Navigate"]
var d: NSMutableDictionary = ["Xcode": "name", "6.1.1": "version", "qq":a]

将字典转化为json数据:

var jsonData = NSJSONSerialization.dataWithJSONObject(dictionary, options:nil, error: nil)

将json转化为字典数据:

let jsonDatas = NSJSONSerialization.JSONObjectWithData(jsonData!, options: .MutableContainers, error: nil) as NSDictionary

json与服务器进行数据交互

1、用NodeJs建立一个简单的web服务,吐出json数据:

var http=require(‘http‘)
var port = ‘8081‘
var data = {‘name‘: ‘jifeng‘, ‘company‘: ‘taobao‘};
http.createServer(function (req, res) {
    res.writeHead(200, {‘Content-Type‘: ‘text/html; charset=UTF-8‘,‘Server‘:‘NodeJs‘});
    res.end(JSON.stringify(data));
}).listen(port, "127.0.0.1");

2、用swift原生类请求数据:

var url = NSURL(string: "http://localhost:8081")
var request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{
    (response, data, error) -> Void in
    if (error? != nil) {
        //Handle Error here
        print(error)
    }else{
        let jsonData = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary
        println(jsonData)
        //Handle data in NSData type
    }
    
})

 

Swift基础知识整理

标签:

原文地址:http://www.cnblogs.com/ericjun/p/4177781.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!