// Copyright © 2015年 曾志良. All rights reserved.
//
//使用NSURLConnection进行数据的提交和获取(POST与GET)
import UIKit
class LANNetworkNSURLConnection: NSObject,NSURLConnectionDataDelegate {
//NSURLConnection同步post请求
func NSURLConnectionSynchronousRequestPost(urlString:String,body:String){
var url:NSURL!
url=NSURL(string: urlString)
let request=NSMutableURLRequest(URL: url)
//编码数据Post数据
let postData=body.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPMethod="POST"
request.HTTPBody=postData
// let body = "score=\(score)&user=\(userid)"//body例子
//响应对象
var response:NSURLResponse?
do{
let received:NSData?=try NSURLConnection.sendSynchronousRequest(request,returningResponse: &response)
let datastring=NSString(data: received!,encoding: NSUTF8StringEncoding)
print(datastring)
}
catch let error as NSError{
print("错误了\(error)")
}
}
//NSURLConnection异步post请求(弃用)
func NSURLConnectionAsynchronousRequestPost(urlString:String,body:String){
var url:NSURL!
url=NSURL(string: urlString)
let request=NSMutableURLRequest(URL: url)
//编码数据Post数据
let postData=body.dataUsingEncoding(NSASCIIStringEncoding)
request.HTTPMethod="POST"
request.HTTPBody=postData
var conn:NSURLConnection!
conn=NSURLConnection(request: request,delegate: self)//9,0以后这个方法弃用
conn.start()
print(conn)
}
//NSURLConnection同步GET请求
func NSURLConnectionSynchronousRequestGet(urlString:String){
var url:NSURL!
url=NSURL(string: urlString)
let request=NSMutableURLRequest(URL: url)
//编码数据Post数据
request.HTTPMethod="GET"
// //NSURLConnection异步GET请求(弃用)
func NSURLConnectionAsynchronousRequestGET(urlString:String){
var url:NSURL!
url=NSURL(string: urlString)
let request=NSMutableURLRequest(URL: url)
//编码数据Post数据
request.HTTPMethod="GET"
var conn:NSURLConnection!
conn=NSURLConnection(request: request,0)">以后这个方法弃用
conn.start()
print(conn)
}
func connection(connection: NSURLConnection,didReceiveResponse response: NSURLResponse)
{
print("请求成功!");
print(response)
}
func connection(connection: NSURLConnection,didReceiveData data: NSData)
{
print("请求成功1!");
let datastring = NSString(data:data,encoding: NSUTF8StringEncoding)
print(datastring)
}
func connectionDidFinishLoading(connection: NSURLConnection)
{
print("请求成功2!");
}
}