我在我的應用程序中登錄頁面,在該頁面中進行身份驗證併發出發布請求。 我將從API提供的API中獲取令牌。 但是,我的代碼沒有在打印日誌上打印任何內容。請幫忙!!如何在Swift中創建'post'HTTP請求?
@IBAction func submit(sender: AnyObject) {
//creating a function that will connect to API
func connectToWebAPI(){
//setting up the base64-encoded credentials
let userName = "user"
let password = "pass"
let loginString = NSString(format: "%@:%@", userName, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(nil)
//creating the request
let url = NSURL(string: "http://www.telize.com/geoip")
var request = NSMutableURLRequest(URL: url!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession.sharedSession()
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let urlConnection = NSURLConnection(request: request, delegate: self)
request.HTTPMethod = "POST"
request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
if (error != nil) {
println(error)
}
else {
// converting the data into Dictionary
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println(jsonResult)
}
})
//fire off the request
task.resume()
}
太棒了!我接受了你的建議,並且它工作正常 – user2832411