如何在Swift中创建GET,POST和PUT请求? [英] How to create a GET, POST, and PUT request in Swift?

查看:274
本文介绍了如何在Swift中创建GET,POST和PUT请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  let URL:NSURL = NSURL(string: http://someserver.com)!
让InfoJSON:NSData?= NSData(contentsOfURL:URL)
让JsonInfo:NSString = NSString(data:InfoJSON !,编码:NSUTF8StringEncoding)!
让GameListAttributions:NSArray = NSJSONSerialization.JSONObjectWithData(InfoJSON !, options:.allZeros,error:nil)!as NSArray

这只对一次接收信息很有帮助,但是我怎样才能在Swift中使用GET,POST和PUT。无论我搜索多少,我都找不到一个关于如何执行的好教程或示例

com))//如果URL不是https
请记住放置ATS异常请求= NSMutableURLRequest(URL:url!)
request.addValue(application / x-www-form-urlencoded, forHTTPHeaderField:Content-Type)//可选
request.HTTPMethod =PUT
let session = NSURLSession(配置:NSURLSessionConfiguration.defaultSessionConfiguration(),delegate:nil,delegateQueue:nil)
let data =username=self@gmail.com& password = password.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = data

let dataTask = session.dataTaskWithRequest(request){(data,response,error) - >无效

如果错误!=无{

//处理错误
}
其他{

让jsonStr = NSString(data:data !,编码:NSUTF8StringEncoding)
print(Parsed JSON:'\(jsonStr)')
}
}
dataTask.resume()


I can connect to a server synchronously with this code snippet in swift.

let URL: NSURL = NSURL(string: "http://someserver.com)!
let InfoJSON: NSData? = NSData(contentsOfURL: URL)
let JsonInfo: NSString = NSString(data:InfoJSON!, encoding: NSUTF8StringEncoding)!
let GameListAttributions: NSArray = NSJSONSerialization.JSONObjectWithData(InfoJSON!, options: .allZeros, error: nil)! as NSArray

This is only good for receiving information all at once, but how would I use a GET, POST, and PUT with Swift. No matter how much I search I can't find a good tutorial or example on how to execute these.

解决方案

let url = NSURL(string: "https://yourUrl.com") //Remember to put ATS exception if the URL is not https
let request = NSMutableURLRequest(URL: url!)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") //Optional
request.HTTPMethod = "PUT"
let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)
let data = "username=self@gmail.com&password=password".dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = data

let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in

    if error != nil {

        //handle error
    }
    else {

        let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("Parsed JSON: '\(jsonStr)'")
    } 
}
dataTask.resume()

这篇关于如何在Swift中创建GET,POST和PUT请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆