Value of http body has no member request - ios

Code:
let request1 = NSMutableURLRequest(URL:NSURL(string: urlString)!)
request1.HTTPMethod = "POST"
request1.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = ["name":"sfsd"]
request1.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: [])
.request(request1)
.responseJSON { response in
// do whatever you want here
switch response.result {
case .Failure(_, let error):
print(error)
case .Success(let responseObject):
print(responseObject)
}
}
I am trying to send json value through POST method
At HttpBody line it is showing error "value of http body has no member request".What is wrong with my code?any help will be appreicated.thanks in advance

You are trying to call the method request on the object returned from dataWithJSONObject, which is an instance of NSData, and NSData does not have such a method. Use Alamofire.request(request1)

Related

Alamofire - add both query parameter and body

I am trying to send a request that should contain both URL parameters and request body in JSON. Backend doesn't recognize the request and returns 400 status code.
This is how I tried to solve the problem
enum MyRequestsRouter: URLRequestConvertible {
case RequestA(paramA: String, bodyInJsonString: String),
RequestB(paramB: String)
var baseURL: URL {
URL(string: "http://127.0.0.1:8080")!
}
var method: HTTPMethod {
switch self {
case .RequestA: return .post
case .RequestB: return .get
}
}
var path: String {
switch self {
case .RequestA: return "/api/a"
case .RequestB: return "/api/b"
}
}
var parameters: Parameters? {
switch self {
case .RequestA(let paramA, let bodyInJsonString):
return [
"paramA": paramA
]
case .RequestB(let paramB):
return ["paramB": paramB]
default:
return nil
}
}
func asURLRequest() throws -> URLRequest {
let url = baseURL.appendingPathComponent(path)
var request = URLRequest(url: url)
request.method = method
switch self {
case let .RequestA(paramA, bodyInJsonString):
// here I am specifying `paramA` value
request = try URLEncoding.default.encode(request, with: parameters)
// here body is already serialized to Json
request.httpBody = Data(bodyInJsonString.utf8)
request.setValue("application/json", "Content-Type")
case let .RequestB(paramB):
request = try URLEncoding.default.encode(request, with: parameters)
}
return request
}
}
And this is how I am making API call
let json: Data = try JSONEncoder().encode(notSerializedBodyObject)
let jsonString = String(data: json, encoding: .utf8)
AF.request(MyRequestsRouter.RequestA(paramA: "paramA", bodyInJsonString: jsonString!)).response { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
print("Error: \(response.error)")
// etc
}
}
As you can see the request URL is supposed to be
http://127.0.0.1:8080/api/a?paramA=paramA plus request body in JSON. But response is 400 Bad request.
How to properly configure Alomofire?
Alamofire's URLEncoding has an initializer that gets destination as parameter. Based on documentation:
Destination defining where the encoded query string will be applied.
.methodDependent by default.
By default .methodDependent case checks the HTTP method of the request and only on .get, .head and .delete requests it encodes the passed parameters in the URL.
Given that fact, you never see paramA in your request (not even in the body) because you override it in the following line:
// here body is already serialized to Json
request.httpBody = Data(bodyInJsonString.utf8)
So, instead of using the default URLEncoding, you can simply call URLEncoding's initializer directly passing as destination the .queryString case like this:
// here I am specifying `paramA` value
request = try URLEncoding(destination: .queryString).encode(request, with: parameters)
// here body is already serialized to Json
request.httpBody = Data(bodyInJsonString.utf8)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
That way you will have a request with paramA in the URL and your JSON as a body.

Swift 3 - issue to create easy request method POST (URLRequestVonvertible)

I am developing an application with Swift 3.0 and IOS 10 in Xcode 8.3.2. But I have a problem when I try to retrieve the JSON from this APIRest (http://schematic-ipsum.herokuapp.com/). What is the problem? Or how you would make the call. If you need more information regarding the code, tell me, but basically, I just want to make a call to that page to recover the biography.
enter image description here
My code is this:
import AlamofireDomain
import Alamofire
import ObjectMapper
class AuthorDAO : SimpleDAO {
func getBiography(_ parameters: Dictionary<String, Int>,
callbackFuncionOK: #escaping
(PropertiesAuthorModel)->(),
callbackFunctionERROR: #escaping (Int,NSError)->()) {
let ulr = NSURL( string: "http://schematic-ipsum.herokuapp.com/" as String)
let request = NSMutableURLRequest(url: ulr! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Constent-Type")
let data = try! JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print(json)
}
request.httpBody = json!.data(using: String.Encoding.utf8.rawValue)
Alamofire.request(request as URLRequest)
.responseJSON { response in
if response.result.isSuccess{
if let status = response.response?.statusCode {
switch(status){
//MARK: CONTROL ON DIFERENTS KINDS OF RESPONSES ON SERVER
case 200:
if let value = response.result.value {
let biographyResponse = Mapper<PropertiesAuthorModel>().map(JSONObject: value)
callbackFuncionOK(biographyResponse!)
}
//case 400: {} ..., case 404: {} ...
default:
break
}
}
}
//MARK: ERROR ON SERVER
else {
var statusCode = -1
if let _response = response.response {
statusCode = _response.statusCode
}
var nsError: NSError = NSError(domain: Constants.UNKNOWN_HTTP_ERROR_MSG,
code: Constants.UNKNOWN_HTTP_ERROR_ID,
userInfo: nil)
if let _error = response.result.error {
nsError = _error as NSError
}
callbackFunctionERROR(statusCode,nsError)
}
}
}
And the error is: "Error Domain=Alamofire.AFError Code=4 "JSON could not be serialized because of error: The data couldn’t be read because it isn’t in the correct format." 400"
The problem is that it does not enter into the "if response.result.isSuccess {" because the result of the response is "nil" and goes directly to the "else". Showing the error that I have commented. Can it be because I have to send the JSON format in the httpBody request? How can I do it?
Your question should be more clear. "What is the problem?" isn't possible to answer without more information.
To issue HTTP request, take a look at Alamofire, an HTTP networking library written in Swift: https://github.com/Alamofire/Alamofire
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}

How to successfully pass string array as parameter alamofire

I have an endpoint that accepts a string array as parameter but I can't get it working with alamofire.
I test my endpoint with postman and it works fine, even in the browser, but with alamofire it fails and just returns the whole thing (as if I didn't put any parameter).
func getQuotes(String url){
//THIS CALL IS NOT WORKING. PARAMETERS ARE NOT SENT PROPERLY - FIX
let stringArray : [String] = ["4250_XSAU", "Test"]
let getQuoteParameters : Parameters = [
//"internal_symbols": stockInternalSymbols
"internal_symbols" : stringArray
]
print("attempting to get quotes on utility queue")
Alamofire.request(url, parameters: getQuoteParameters).responseJSON{ response in
print(response)
/* if (response.result.value != nil){
let jsonResponse = JSON(response.result.value!)
print(jsonResponse)
}
*/
}
}
Am I doing something wrong? When I go to url + "?internal_symbols=["4250_XSAU","Test"] on my browser, or postman, it works just fine.
I also tried setting my "getQuoteParamaters" variable as
let getQuoteParameters : Parameters = [
"internal_symbols" : ["4250_XSAU", "Test"]
]
but it doesn't work neither... it should be the same thing.
Just to clarify, this request ignores completely my parameters, when it should send the array to my backend.
You can simply pass your string array in converting it into a JSON format.Like in the sample code given below:
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = ["06786984572365", "06644857247565", "06649998782227"]
request.httpBody = try! JSONSerialization.data(withJSONObject: values)
Alamofire.request(request)
.responseJSON { response in
// do whatever you want here
switch response.result {
case .failure(let error):
print(error)
if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
print(responseString)
}
case .success(let responseObject):
print(responseObject)
}
}
My solution in Swift 3:
let text: [String] = ["location.branches.longitude", "location.branches.latitude"]
let params: Parameters = [
"_source": text
]
Try by add encoding standard in your request, like JSONEncoding.default
func getQuotes(String url){
//THIS CALL IS NOT WORKING. PARAMETERS ARE NOT SENT PROPERLY - FIX
let stringArray : [String] = ["4250_XSAU", "Test"]
let getQuoteParameters : Parameters = [
//"internal_symbols": stockInternalSymbols
"internal_symbols" : stringArray
]
print("attempting to get quotes on utility queue")
Alamofire.request(url, method: .post, parameters: getQuoteParameters, encoding: JSONEncoding.default).responseJSON{ response in
print(response)
/* if (response.result.value != nil){
let jsonResponse = JSON(response.result.value!)
print(jsonResponse)
}
*/
}
Thanks.

Alamofire NSURLRequest via POST method doesn't work

I'm new to swift and iOS and trying to use Alamofire and router for them, which returns NSMutableURLRequest, but my code didn't work. So I just made one NSURLRequest for test, and requested it but results was same.
Here is my code. I'm currently using Alamofire and SwiftyJSON.
let params = ["Id": "1234567", "Token": "something"]
let url = NSURL(string: "myurl")
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = Alamofire.Method.POST.rawValue
let encoding = Alamofire.ParameterEncoding.JSON
(request, _) = encoding.encode(request, parameters: params)
Alamofire.request(request)
.validate()
.responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
let token = json["token"].stringValue
let error = json["error"].stringValue
print("token : \(token), error : \(error)")
}
case .Failure(let error):
// TODO:
print(error)
}
}
Above code sends request without parameters. Are there any errors on my code?
I've checked your code and before executing encode function your request.HTTPBody is empty, but after it has some data like
Optional<NSData>
- Some:<7b22546f 6b656e22 3a22736f 6d657468 696e6722 2c224964 223a2231 32333435 3637227d>
When I call print(response.request?.HTTPBody) in Alamofire response block, I get the parameters as NSData and the HTTPBody includes the same data as before sending the request so it works.
Try also change the response from responseJSON to responseString, because if your response can't be parsed to JSON you get Failure.
I think you should check on your URL site if you get correct data.
Instead of your solution I use
Alamofire.request(method, url, parameters: parameters, encoding: .JSON) .responseString{ response in}
is the same but shorter and everything is as parameters.

Alamofire data send with HTTPBody issue

I'm trying to make api request with Alamofire. Data want to send with body. heare is what im doing.
let URL : String = "\(BaseUrl.sharedInstance.URL)\(EndPoint)"
do {
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(RequestData, options: options)
let jsons = NSString(data: data, encoding: NSUTF8StringEncoding)
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL)!)
mutableURLRequest.HTTPMethod = "POST"
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
Alamofire.request(mutableURLRequest)
.response { request, response, data, error in
print(request)
let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(dataString)
print(response)
print(error)
}
} catch {
print("JSON serialization failed: \(error)")
}
anyone have idea about it.
Alamofire.request(.POST, URLString, parameters: parameters, encoding: .JSON, headers: headerss).responseJSON
{
response in switch response.result
{
case .Success(let JSON):
let response = JSON as! NSDictionary
print (response);
onSuccess (response)
//example if there is an id
case .Failure(let error):
onFailure (error);
print("Request failed with error: \(error)")
}
}

Resources