[英]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.