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.default
to 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
How to Save Cgimage to Data in Swift
Uiimage Created from Mtkview Results in Color/Opacity Differences
How to Add Auto-Complete Comment in Xcode (Swift)
Xcode: Could Not Load Modelio.Framework, Scenekit.Framework, etc
Iaps Actually Validating the Receipt (Swift)
Swift 3 and Firebase: Retrieve Auto Id Value from Snapshot
Proper Model for Multiple Alamofire Requests for Multiple Websites
Convert or Cast Object to String
Converting String to Data in Swift 3.0
Two Weak Variables Referencing Each Other in Swift
Swift Arc4Random_Uniform(Max) in Linux
How to Set an Ordered Relationship with Nspersistentcloudkitcontainer
Swift 3: How to Pinch to Scale and Rotate Uiimageview