博客> swift 网络请求
swift 网络请求
2017-05-26 06:13 评论:1 阅读:337 boluo20141010
ios swift 网络请求 xcode7.3

swift里面的网络请求内容和oc没有什么区别 ,唯一的区别应该就是swift里面的闭包与oc中的blcok回调, 这里简单说一个swift里面的post请求 // Copyright © 2016年 sctengsen-imac03. All rights reserved. //

import UIKit typealias closure = (dict:NSDictionary?,jsonString:String?) ->Void class TSHttpManagerSwift: NSObject,NSURLConnectionDataDelegate {

var backClosure:closure?
var resulteData = NSMutableData()

func post(url:String,para:NSDictionary,complete:closure)  -> Void {

   backClosure = complete

    let path = NSURL(string: url)

    let mutablerequest = NSMutableURLRequest(URL: path!)

    mutablerequest.HTTPMethod = "post"//设置请求方式

    let data = NSKeyedArchiver.archivedDataWithRootObject(para)

    mutablerequest.HTTPBody = data //设置请求体

    mutablerequest.timeoutInterval=10//设置延时

    let connection = NSURLConnection(request: mutablerequest, delegate: self, startImmediately: true)

    connection!.start()

}

//connection代理方法 与oc里面相同的内容 开始响应请求 func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {

    let resp = response as! NSHTTPURLResponse

    resulteData.length=0

    print("开始响应请求\(resp.statusCode)")

}

// 开始接收数据
func connection(connection: NSURLConnection, didReceiveData data: NSData) {

    resulteData.appendData(data)

}

// 数据请求完成
func connectionDidFinishLoading(connection: NSURLConnection) {

    let dict = try! NSJSONSerialization.JSONObjectWithData(resulteData, options: .MutableContainers) as! NSDictionary

    let jsonString = String(data: resulteData, encoding: NSUTF8StringEncoding)

   self.backClosure!(dict: dict,jsonString: jsonString)

}
//数据请求失败
func connection(connection: NSURLConnection, didFailWithError error: NSError) {

    print("请求失败了没有网络或者网络超时等情况\(error)")

   self.backClosure?(dict: nil,jsonString: nil)
}

}

上面就是一个封装好的简单的数据请求类,下面开始应用 // func click(button:UIButton) -> () {

   let ts = TSHttpManagerSwift()
    let para = ["phone":"13684030501",
    "token":"8bee6d964446b4e5812fcd0e92a4d64e"]
   ts.post("http://211.149.203.140/Api/User/hobbyList", para: para) { (dict,string) in

    print(dict)

    }

// dict里面的内容 { hobby = ( { id = 1; name = "\U5403\U996d\U7761\U89c9"; }, { id = 2; name = "\U770b\U4e66"; }, { id = 3; name = "\U8fd0\U52a8\U5065\U8eab"; }, { id = 4; name = "\U65c5\U6e38\U6444\U5f71"; }, { id = 5; name = "\U81ea\U9a7e\U8d8a\U91ce"; }, { id = 6; name = "\U97f3\U4e50\U5f71\U89c6"; }, { id = 7; name = "\U5f92\U6b65"; }, { id = 8; name = "\U94b1\U94b1\U94b1"; }, { id = 9; name = "\U7f51\U7edc\U6e38\U620f"; } ); }

收藏
0
sina weixin mail 回到顶部