1

我正在做一个提出请求的演示应用Swift 2程序HTTP POST。但是不明白为什么我的请求没有到达服务器。我正在使用Alamofire 3.0, Xcode 7.2, swift 2.0. 我Alamofire根据此链接安装了 pod :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 = (
        {
        }
    );
})

我不明白为什么它没有到达服务器。

4

1 回答 1

0

你以前做过吗?info.plist 中的应用程序传输安全性。 https://github.com/Alamofire/Alamofire 其次,参数没有任何东西。应该将您的字符串更改为字典。

您可以使用 json 将字符串制作成字典。

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。

于 2015-12-29T10:34:15.103 回答