我正在尝试做这样的事情:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
request.HTTPMethod = @"POST";
NSString *stringData = @"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
这是我到目前为止所做的:
var url = NSURL(string: "some url")
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
var dataString = "some data"
var requestBodyData: NSData = dataString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) as NSData
request.HTTPBody = requestBodyData
var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)
println("sending request...")
connection.start()
然而,var requestBodyData:行抛出第一块石头“无法将表达式的NSData类型转换为类型NSData”
有人想要权衡吗?
答案 0 :(得分:10)
stringByAddingPercentEscapesUsingEncoding
返回一个字符串而不是NSData对象。根据{{3}}回答,您需要使用它来转换为NSData实例:
let data = (anySwiftString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
答案 1 :(得分:1)
使用 Alamofire 发送HTTP POST请求
let request = NSMutableURLRequest(URL: NSURL(string: "https://www.google.com")!)
request.HTTPMethod = "POST"
let body = "email=\(email)&access_token=\(token)"
request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
Alamofire.request(request).responseJSON { response in
NSLog("response.request: \(response.request)") // original URL request
NSLog("esponse.response: \(response.response)") // URL response
switch response.result {
case .Success:
NSLog("Validation Successful")
case .Failure(let error):
// Logout
NSLog("\(error), \(String(data: response.data!, encoding: NSUTF8StringEncoding))")
return
}
// Save sip account information to NSUserdefaults
if let json = response.result.value as? [String: AnyObject]{
// Do your stuff
}
}