[英]POST request not working while using Alamofire pod in swift2?
我正在Swift 2
中做一个演示应用程序,该应用程序发出HTTP
POST
请求。 但是不明白为什么我的请求没有到达服务器。 我正在使用Alamofire 3.0
, Xcode 7.2
和Alamofire 3.0
swift 2.0
。 我根据此链接安装了Alamofire
吊舱: https : //github.com/Alamofire/Alamofire#requirements
我的弦是
str = "{videos{title,videourl,imageurl}}"
这是我的代码:
Alamofire.request(
.POST,
url,
parameters: Dictionary(),
encoding: .Custom({
(convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
mutableRequest.setValue("application/graphql", forHTTPHeaderField: "Content-Type")
mutableRequest.HTTPBody = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return (mutableRequest, nil)
}),
headers: nil
).responseJSON{
(JSON) -> Void in
if JSON.result.value != nil
{
print(JSON.result.value)
self.delegate.successReponse(JSON.result.value!, withType: type)
}
else
{
}
}
当我打印JSON.result.value
,它显示如下:
Optional({
errors = (
{
}
);
})
我不明白为什么它无法到达服务器。
你以前做过吗? info.plist中的App Transport Security。 https://github.com/Alamofire/Alamofire其次,参数没什么东西。 应该将您的字符串更改为Dictionary。
您可以使用json将字符串转换为Dictionary。
let data = changestring.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
var dict = NSDictionary()
do{
//dict = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
dict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSDictionary
}
catch{
}
NSLog("this is dict \(dict)")
或者,您也可以将NSDictionary传递给参数。
Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON)
如果您希望使用其他方法进行HTTP POST和GET,则此链接适合您: https : //github.com/RYANCOAL/swift-with-AFNetworking/blob/master/TestHTTPTests/TestHTTPTests.swift
手动验证Alamofire.validate(contentType:[“ application / json”])可以搜索contentType的值,因为我不知道它可以/不能设置contentType。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.