Swift 2.0, Alamofire: Set Cookies in Http Post Request

POST request using alamofire 2.0 and Swift 2.0

I think that's a optional type problem. Can you try to add ! to your variables such as:

var parametersToSend = [
"firstName": firstNameToSend!,
"lastName": lastNameToSend!,
"mailAddress": mailAddressToSend!,
"password": passwordToSend!
]

Make POST request with alamofire

If you're testing with a real iPhone, you should change the host from localhost to your Mac's ip address and make sure you iPhone and Mac in the same wireless network.

If you're testing with a simulator, it should work. Maybe you can change localhost to 127.0.0.1.

The error is due to wrong url. You can test in Safari in your device to see if it works.

How to send token string (jwt) as Cookie in Alamofire Post request in swift?

You can try setting the HTTPCookieStorage in the session.

Swift 2

let properties = [
NSHTTPCookieDomain: "httpbin.org",
NSHTTPCookiePath: "/post",
NSHTTPCookieName: "foo",
NSHTTPCookieValue: "bar",
]

let cookie = NSHTTPCookie(properties: properties)!
manager.session.configuration.HTTPCookieStorage?.setCookie(cookie)

Swift 3

let properties = [
HTTPCookiePropertyKey.domain: "httpbin.org",
HTTPCookiePropertyKey.path: "/post",
HTTPCookiePropertyKey.name: "foo",
HTTPCookiePropertyKey.value: "bar",
]

let cookie = HTTPCookie(properties: properties)!
manager.session.configuration.httpCookieStorage?.setCookie(cookie)

Alomofire POST request in swift

Request not always in JSON please check your request :

Following are examples to use Alamofire with the Swift 2 :

GET - JSON

Alamofire.request(.GET, "http://api.androidhive.info/contacts/", parameters: nil, encoding: .JSON, headers: nil).responseJSON { (req, res, json) -> Void in
print("\(res?.allHeaderFields)")
print("\(json.value!)")
}

POST - without JSON

Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar"], encoding: .URL, headers: nil).response { (req, res, data, error) -> Void in
print(res)
print(data)

let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(dataString)
}

iOS http POST using Alamofire

I figured it out.

The solution using Alamofire:

        let data = [
"To" : mobileInput.text as String!,
"From" : twilioSMSFrom,
"Body" : String(code) as String
]

Alamofire.request(.POST, "https://\(twilioUsername):\(twilioPassword)@api.twilio.com/2010-04-01/Accounts/\(twilioUsername)/Messages", parameters: data)
.responseJSON { response in
print(response.request)
print(response.response)
print(response.result)
}

Alamofire POST request with Swift 2

If you see the documentation in the branch Swift2.0 you can see that the responseJSON function has changed as the error says, it have now three parameters but you can catch the error too, lets take a look:

public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject>) -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}

Now it returns an enum Result<AnyObject> and according to the doc :

Used to represent whether a request was successful or encountered an error.

- Success: The request and all post processing operations were successful resulting in the serialization of the
provided associated value.
- Failure: The request encountered an error resulting in a failure. The associated values are the original data
provided by the server as well as the error that caused the failure.

And it have inside an property entitled error, with the following doc:

/// Returns the associated error value if the result is a failure, `nil` otherwise.
public var error: ErrorType? {
switch self {
case .Success:
return nil
case .Failure(_, let error):
return error
}
}

Then if you follow this test case inside Alamofire you can see how to get the error properly:

func testThatResponseJSONReturnsSuccessResultWithValidJSON() {
// Given
let URLString = "https://httpbin.org/get"
let expectation = expectationWithDescription("request should succeed")

var request: NSURLRequest?
var response: NSHTTPURLResponse?
var result: Result<AnyObject>!

// When
Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseJSON { responseRequest, responseResponse, responseResult in
request = responseRequest
response = responseResponse
result = responseResult

expectation.fulfill()
}

waitForExpectationsWithTimeout(defaultTimeout, handler: nil)

// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertTrue(result.isSuccess, "result should be success")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.data, "result data should be nil")
XCTAssertTrue(result.error == nil, "result error should be nil")
}

UPDATE:

Alamofire 3.0.0 introduces a Response struct. All response serializers (with the exception of response) return a generic Response struct.

public struct Response<Value, Error: ErrorType> {
/// The URL request sent to the server.
public let request: NSURLRequest?

/// The server's response to the URL request.
public let response: NSHTTPURLResponse?

/// The data returned by the server.
public let data: NSData?

/// The result of response serialization.
public let result: Result<Value, Error>
}

So you can call it like the following way:

Alamofire.request(.GET, "http://httpbin.org/get")
.responseJSON { response in
debugPrint(response)
}

You can read more about the migration process in the Alamofire 3.0 Migration Guide.

I hope this help you.

Alamofire POST parameters doesn't come through

I found a solution to my problem, I changed encoding: JSONEncoding.defaultto encoder: URLEncodedFormParameterEncoder(destination: .httpBody)

the request function looks likes this now

AF.request(urlPath, method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody)).responseJSON { (response) in

//some code

}


Related Topics



Leave a reply



Submit