在swift2中使用Alamofire pod时POST请求无效?

时间:2015-12-29 09:44:21

标签: ios swift xcode7.2

我正在Swift 2做一个提出HTTP POST请求的演示应用。但不明白为什么我的请求没有命中服务器。 我正在使用Alamofire 3.0Xcode 7.2swift 2.0。 我根据此linkhttps://github.com/Alamofire/Alamofire#requirements

安装了Alamofire广告连播

我的字符串是

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 = (
        {
        }
    );
})

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

1 个答案:

答案 0 :(得分:0)

你以前做过吗? info.plist中的App Transport Security。 https://github.com/Alamofire/Alamofire 其次,参数没有任何东西。应该将您的字符串更改为Dictionary。

您可以使用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。