ios php get post请求接口,IOS 苹果原生Get与POST操作网络数据

一、GET操作

let url : NSURL = NSURL(string: String(format: "http://xxx/ywuserinfo/index.php?action=IMEISet&userphone=%@&IMEI=%@" , self.TextField_Phone.text!.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!,(self.defaults.objectForKey("loginIMEIFlag1") as! String).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!))!

//创建请求对象

let request : NSURLRequest = NSURLRequest(URL: url)

//获取会话对象

let session: NSURLSession = NSURLSession.sharedSession()

//创建一个task发送请求

let task: NSURLSessionDataTask = session.dataTaskWithRequest(request) { (data, response, error) in

if error == nil {

do{

//对收到的数据进行json进行解析

if let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)as? NSDictionary{

let result = dict.objectForKey("IMEISetFlag") as! String

dispatch_async(dispatch_get_main_queue(), { () -> Void in

if result == "1" {

//返回访问成功,执行成功之后的操作

}

})

}

}catch{

print("错误")

}

}

}

//执行任务

task.resume()

将数据传到数据库中有中文时

字符串.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

二、POST操作

//创建url路径对象

let url: NSURL = NSURL(string: String(format: "http://xxx/ios/ywuserwater/index.php"))!

//创建请求对象,分别设置网络方法以及请求参数

let request = NSMutableURLRequest(URL: url)

request.HTTPMethod = "POST"

let args:NSString = NSString(format: "action=waterInsert&username=%@&userphone=%@&IMEI=%@&dormitory=%@&usewater=%@&usemoney=%@&fortime=%@&isnormal=%@" , "1","18879026851","1","408","1","1","20170101","1")

request.HTTPBody = args.dataUsingEncoding(NSUTF8StringEncoding)

//获取会话对象

let session: NSURLSession = NSURLSession.sharedSession()

//创建一个task发送请求

let task: NSURLSessionDataTask = session.dataTaskWithRequest(request) { (data, response, error) in

if error == nil {

do{

if let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)as? NSDictionary{

let result = dict.objectForKey("waterInsertFlag") as! String

dispatch_async(dispatch_get_main_queue(), { () -> Void in

if result == "1" {

print("数据库插入成功")

}else if result == "0"{

print("数据库插入失败")

}

})

}

}catch{

print("错误")

}

}

}

//执行任务

task.resume()

iOS POST需要同步请求时

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值