1,使用POST方式提交数据(用户ID和分数) (1)同步请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //保存分数 func savescore(score: Int ,userID: String ) { let urlString: = "http://www.hangge.com/" var url: NSURL ! url = (string:urlString) request = NSMutableURLRequest ( URL :url) body = "score=\(score)&user=\(userID)" //编码POST数据 postData = body.dataUsingEnCoding( NSUTF8StringEnCoding ) //保用 POST 提交 request. httpMethod "POST" httpBody = postData //响应对象 response: NSURLResponse ? do{ //发出请求 received: NSData ? = try NSURLConnection .sendSynchronousRequest(request, returningResponse: &response) datastring = Nsstring (data:received!,enCoding: NSUTF8StringEnCoding ) print (datastring) }catch error as NSError { //打印错误消息 (error.code) (error.description) } } |
(2)异步请求
import UIKit class scoreController : NSObject NSURLConnectionDataDelegate { //保存分数 savescore(score: Int ) { "http://www.hangge.com/savescore.php" ! url = NSURL (string:urlString) :url) "score=\(score)&user=\(userID)" @H_301_349@//编码POST数据 postData = body.dataUsingEnCoding( NSASCIIStringEnCoding ) //保用 POST 提交 "POST" = postData conn: ! conn = NSURLConnection (request: request,delegate: self ) conn.start() (conn) } connection(connection: ) ( "请求成功!" ); (response) } NSData ) { "请求成功1!" ); (data:data,monospace!important; min-height:auto!important; background:none!important">) (datastring) } connectionDIDFinishLoading(connection: ) { "请求成功2!" ); } } |
2,使用GET方式获取数据(用户ID对应的分数) (1)同步请求
//获取分数 getscore(user: ){ "http://www.hangge.com/getscore.php?user=\(user)" "GET" @H_555_502@//响应对象 response: NSURLResponse ? do{ //发出请求 ? = try ) (datastring) { //打印错误消息 (error.code) (error.description) } } |
(2)异步请求
//获取分数 "http://hangge.com/getscore.php?user=\(user)" url: request = NSMutableURLRequest "GET" ! conn = ) conn.start() (conn) } ) { ); (response) connection(connection: ) { ); datastring = Nsstring ) (datastring) //解析 JsON 数据 do { Json : AnyObject ! = try NSJsONSerialization . JsONObjectWithData (data, options: NSJsONReadingOptions AllowFragments ) score = Json.objectForKey( "score" ) as ! Int (score) as NSError { //打印错误消息 (error.code) (error.description) } } connectionDIDFinishLoading(connection: ) { ); } |
原文出自: www.hangge.com 转载请保留原文链接: http://www.hangge.com/blog/cache/detail_670.html 总结
以上是内存溢出为你收集整理的Swift - 使用NSURL进行数据的提交和获取(POST与GET)全部内容,希望文章能够帮你解决Swift - 使用NSURL进行数据的提交和获取(POST与GET)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)