Alamofire returns wrong encoding
You can use NSUTF8StringEncoding
with Alamofire's responseString
method:
Alamofire.request(.GET, "http://my1test.ru/applejesus.php?task=getCategory&categoryNumber=1")
.responseString(encoding: NSUTF8StringEncoding) { (request, response, string, error) -> Void in
if let result = string {
println(result)
}
}
Result:
picture{http://ipic.su/img/img7/fs/ProdukciyaApple.1438079721.png},title{Продукция Apple}
Incorrect response from Alamofire?
As the documentation says:
By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling
validate()
before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.
E.g.
Alamofire.request(url, method: .post, encoding: JSONEncoding.default)
.validate()
.responseJSON { response in
...
}
With validate
, non 2xx responses will now be treated as errors.
alamofire is not preparing correct url
Below is what I did
Swift3
Remove square brackets for GET request
struct CustomGetEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try URLEncoding().encode(urlRequest, with: parameters)
request.url = URL(string: request.url!.absoluteString.replacingOccurrences(of: "%5B%5D=", with: "="))
return request
}
}
...
Alamofire.request("http://example.com", method: .get, parameters: ["foo": ["bar1", "bar2"]], encoding: CustomGetEncoding())
Remove square brackets for POST request
struct CustomPostEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try URLEncoding().encode(urlRequest, with: parameters)
let httpBody = NSString(data: request.httpBody!, encoding: String.Encoding.utf8.rawValue)!
request.httpBody = httpBody.replacingOccurrences(of: "%5B%5D=", with: "=").data(using: .utf8)
return request
}
}
...
Alamofire.request("http://example.com", method: .post, parameters: ["foo": ["bar1", "bar2"]], encoding: CustomPostEncoding())
Swift2
Remove square brackets for GET request
let parameterEncoding = ParameterEncoding.Custom { requestConvertible, parameters in
let (mutableRequest, error) = ParameterEncoding.URL.encode(requestConvertible, parameters: parameters)
mutableRequest.URL = NSURL(string: mutableRequest.URLString.stringByReplacingOccurrencesOfString("%5B%5D=", withString: "="))
return (mutableRequest, error)
}
Alamofire.request(.GET, "http://example.com", parameters: ["foo": ["bar1", "bar2"]], encoding: parameterEncoding)
Remove square brackets for POST request
let parameterEncoding = ParameterEncoding.Custom { requestConvertible, parameters in
let (mutableRequest, error) = ParameterEncoding.URL.encode(requestConvertible, parameters: parameters)
let httpBody = NSString(data: mutableRequest.HTTPBody!, encoding: NSUTF8StringEncoding)!
mutableRequest.HTTPBody = httpBody.stringByReplacingOccurrencesOfString("%5B%5D=", withString: "=").dataUsingEncoding(NSUTF8StringEncoding)
return (mutableRequest, error)
}
Alamofire.request(.POST, "http://example.com", parameters: ["foo": ["bar1", "bar2"]], encoding: parameterEncoding)
Reference
Alamofire Custom Parameter Encoding
You have a couple questions in here. Let's break them down 1x1.
Compiler Issue
Your compiler issue is due to the fact that your return tuple is the wrong type. In Alamofire 1.3.0, we changed the return type to be an NSMutableURLRequest
which ends up making things much easier overall. That should fix your compiler issue.
Setting the HTTPBody
Now you have a couple options here.
Option 1 - Encode Data as JSON
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters!, options: options)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
From what you posted I'm assuming you actually want .URL encoding for the parameters.
Option 2 - Use the .URL Case
let parameters: [String: AnyObject] = [:] // fill in
let encodableURLRequest = NSURLRequest(URL: URL)
let encodedURLRequest = ParameterEncoding.URL.encode(encodableURLRequest, parameters).0
let mutableURLRequest = NSMutableURLRequest(URL: encodedURLRequest.URLString)
mutableURLRequest.HTTPMethod = "POST"
mutableURLRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
Alamofire.request(mutableURLRequest)
.response { request, response, data, error in
print(request)
print(response)
print(error)
}
Hopefully that helps get you going. Best of luck!
Alamofire Encoding issue
try it like this
enum GoogleRouter: URLRequestConvertible {
//the base url (REMOVE THE ? MARK)
static let baseURLString = "https://maps.googleapis.com/maps/api/geocode/json"
//the router
case FetchCoordinatesFromPostcode([String:Any]) //set the case like this
var method: HTTPMethod {
switch self {
case .FetchCoordinatesFromPostcode:
return .get
}
}
//WE Won't be needing path, so lets just remove it
/*var path: String {
switch self {
case .FetchCoordinatesFromPostcode(let postcode):
return "?address=\(postcode)&key=MY_KEY"
}
}*/
func asURLRequest() throws -> URLRequest {
//get the url from string
let url = try GoogleRouter.baseURLString.asURL()
//prepare urlrequest
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue
switch self {
case .FetchCoordinatesFromPostcode(let parameters):
urlRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters)
}
return urlRequest
}
}
func testCall() {
let parameters = ["addres":"myAddress","key":"MY_KEY"]
let request = Alamofire.request(GoogleRouter.FetchCoordinatesFromPostcode(parameters))
request.validate().responseJSON { (response) in
//Do The Thing
}
}
Getting bad request error with alamofire JSON request
The API expects the parameters to be sent as JSON, but you are sending as URL encoded.
Try using JSONParameterEncoder.default
as the encoder instead of URL encoding.
Check Usage from the docs: POST request with JSON Parameters
let parameters: Parameters = [
"registrationNumber" : "myreg"
]
AF.request(url, method: .post, parameters: parameters, encoder: JSONParameterEncoder.default)
Failed response from **Alamofire** in swift 5
As it is throwing error related to Local, I think some language is defined and it doesn't accept * for Accept-Language
header, try sending "en" in the header Accept-Language
.
Check subtags for language:
http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry :
Test Code:
func callAPI() {
let params: Parameters = ["phoneNumber":"911234567890", "countryCode" : "91"]
let headers = [
"deviceId" : "jdhcbkerfjkr",
"osVersion": "3.2.3",
"deviceType": "ANDROID",
"resolution": "122x122",
"buildNumber": "3.2.1",
"Accept-Language": "en"]
AF.request("[Test-URL]",
method: .post,
parameters: params,
encoding: JSONEncoding.default,
headers: HTTPHeaders.init(headers)).response { response in
print(String(data: response.data!, encoding: .utf8)!)
}
}
Related Topics
Mfmailcomposeviewcontroller Error [Mc] Filtering Mail Sheet Accounts for Bundle Id
Infer Closure Return Type from Closure Body When Working with Generics
Why Use an Extra Let Statement Here
Is There a Github Markdown Language Identifier for Swift Code
How to Convert 4 Bytes to a Swift Float
Mandatory Init Override in Swift Uinavigationcontroller Subclass
Swift: Incrementing Label with Delay
Swift: How to Flush Stdout After Println
Using Uilexicon to Implement Autocorrect in iOS 8 Keyboard Extension
Appdelegate Segue Alternative Pass Data
Integer Literal Overflows When Stored into 'Int'
How to 'Addtarget' to Uilabel in Swift
Swift Build' on Terminal Throw 'Error: Root Manifest Not Found'