1

I’m doing a Demo App in Swift 2 that makes an HTTP POST request. But don’t understand why my request doesn't hit the server. I’m using Alamofire 3.0, Xcode 7.2, swift 2.0. I installed the Alamofire pod based on this link: https://github.com/Alamofire/Alamofire#requirements

And my string is

str = "{videos{title,videourl,imageurl}}"

Here my code is:

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
        {   
        }
}

When i’m printing the JSON.result.value, it’s showing like this:

Optional({
    errors = (
        {
        }
    );
})

I don’t understand why it is not reaching to the server.

Ramakrishna
  • 712
  • 8
  • 26

1 Answers1

0

Have your do it before ? App Transport Security in info.plist. https://github.com/Alamofire/Alamofire Secondly, the parameters 's don't have any things. It should be change your string to Dictionary.

Your can use json to make string to 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)")

Or you can just past NSDictionary to parameters.

Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters, encoding: .JSON)

If your want to others method for HTTP POST and GET, this link is Suitable for you: https://github.com/RYANCOAL/swift-with-AFNetworking/blob/master/TestHTTPTests/TestHTTPTests.swift

Manual Validation Alamofire.validate(contentType: ["application/json"]) can search the value for contentType, by I don't know it can / cannot be set contentType.

jcaron
  • 17,302
  • 6
  • 32
  • 46