Alamofire put with array of ObjectMapper - ios

I have array of ObjectMapper:
var arr = [Model]
now how can i use Alamofire to send this array to server with .PUT or .POST method?
Alamofire.request(.PUT, Config().apiGroup, parameters: arr, encoding: .JSON)
it says that parameters type is [String : AnyObject]?.
I tried with this too:
var params = Array<AnyObject>()
for entry in arr {
params.append(Mapper().toJSON(entry))
}
and then to pass params to parameters, but still getting error.
Any solution?

You can do this to convert:
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let pjson = attendences.toJSONString(prettyPrint: false)
let data = (pjson?.data(using: .utf8))! as Data
request.httpBody = data
Alamofire.request(request).responseJSON { (response) in
print(response)
}

Related

How i can Load POST URLRequest with parameter in WKWebView?

Sorry For this my English is weak
I try many types of a solution but not working in Xcode 11.2.1 and swift 5
I try this
var urlRequest = URLRequest(url: URL(string: "https://xxxxxx/login")!)
urlRequest.httpMethod = "POST"
let params = [
"username": SessionManager.shared.username!,
"password": SessionManager.shared.password!,
"vhost": "standard"
]
let postString = self.getPostString(params: params)
urlRequest.httpBody = postString.data(using: .utf8)
webView.load(urlRequest)
...
//helper method to build url form request
func getPostString(params:[String:String]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
and this
Post Request with Parameter
And also try to add below lines in my code
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
But not Working
I fire the Request because not working the WKWebView screen is Open but not Load request.
If I not set navigationDelegate and open normal URL then it is working completely
If I set navigationDelegate then blank page come in all Request Like Normal URL fire or post parameter URL fire, All are coming to Blank Page in
I can't understand what is the Problem with WKWebView
Please help me.
Thanks in advance
The request body uses the same format as the query string:
parameter=value&also=another
Therefore the content type of your request is of type application/x-www-form-urlencoded :
let postString = self.getPostString(params: params)
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postString.data(using: .utf8)
webView.load(urlRequest)
Try this, we will initiate a POST request using URLSession convert the data returned by the server to String and instead of loading the url we will use loadHTMLString which will:
Set the webpage contents and base URL.
and the content is our converted string::-
var request = URLRequest(url: URL(string: "http://www.yourWebsite")!)
request.httpMethod = "POST"
let params = "Your Parameters"
request.httpBody = params.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data : Data?, response : URLResponse?, error : Error?) in
if data != nil {
if let returnString = String(data: data!, encoding: .utf8) {
self.webView.loadHTMLString(returnString, baseURL: URL(string: "http://www.yourWebsite.com")!)
}
}
}
task.resume()
I think we not need to use URLSession.dataTask, simply create URLRequest and declare your method + with stating header fields like this:
private final func postRequestToURL(_ urlString: String) {
guard let url = URL(string: urlString) else {
debugPrint("Error: Invailed URL!")
return
}
var parameters = Parameters()
parameters["name"] = "Example"
parameters["surname"] = "ExmpleExample"
parameters["timeZone"] = "MiddleEast/MENA"
parameters["test"] = "YES"
var urlRequest = URLRequest(url: url)
urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.allowsCellularAccess = true
urlRequest.httpMethod = "POST"
let postString = parameters.getPostString()
urlRequest.httpBody = postString.data(using: .utf8)
if let wkNavigation = self.webView.load(urlRequest) {
debugPrint("Success: \(wkNavigation.description)")
} else {
debugPrint("Failure: Cannot load current request.")
}
}
Here we can convert our parameters to String by this extension:
public extension Dictionary where Key == String, Value == Any {
func getPostString() -> String {
var data = [String]()
for(key, value) in self {
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
}
I am using this code over my commercial app.
Additional info: I allowed request eligible to run over cellular by marking allowsCellularAccess = true this is optional

How to add urlencoded parameter to httpBody in urlRequest

i have created one common class for alamofire request
i want to send parameters as aplication/x-www-form-urlencoded
how to add the parameters to my urlRequest
i have managed to add parameters as application/json to urlRequest using below code
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
i need something similar for aplication/x-www-form-urlencoded
here is my parameters
case .ewalletData :
return [K.APIParameterKey.token :"OP8JHOEOZ5KJW1X",K.APIParameterKey.fromMobile:"true",K.APIParameterKey.adminName:"binaryecom",K.APIParameterKey.limit:"100",K.APIParameterKey.offset:"0",K.APIParameterKey.userName:"OC6DGH"]
here is the code it works for me in swift 4:
let postString = "your parameter="+value+"&your parameter="+value
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request, completionHandler: completionHandle)
task.resume()
try this :
guard let request_url = URL(string: Url) else { return }
let parameterDictionary = ["your parameter" : value]
var request = URLRequest(url: request_url)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
request.setValue("aplication/x-www-form-urlencoded", forHTTPHeaderField: "String")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
return
}
request.httpBody = httpBody

How to send a request with alamofire with xml Body

I installed Alamofire in my project and now here is what I have done.
I installed postman and I put my url and inside body a xml object and I got my result.
Here is a picture of what I exactly have done with postman
How can I now use Alamofire or SWXMLHash to send it as I send it with postman
Thanks in advance!
EDIT
I tried this from another question:
Alamofire.request(.POST, "https://something.com" , parameters: Dictionary(), encoding: .Custom({
(convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
let data = (self.testString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
mutableRequest.HTTPBody = data
return (mutableRequest, nil)
}))
.responseJSON { response in
print(response.response)
print(response.result)
}
}
But it didn't send anything
This is the log:
Optional( { URL:
https://something.com } { status code: 200, headers {
Connection = "keep-alive";
"Content-Length" = 349;
"Content-Type" = "application/xml";
Date = "Wed, 02 Nov 2016 21:13:32 GMT";
Server = nginx;
"Strict-Transport-Security" = "max-age=31536000; includeSubDomains"; } })
FAILURE
EDIT
NEVER FORGET TO PASS parameters if you don't have simple add this , parameters: Dictionary()
Using Swift 3 and Alamofire 4
let stringParams : String = "<msg id=\"123123\" reqTime=\"123123\">" +
"<params class=\"API\">" +
"<param name=\"param1\">123213</param>" +
"<param name=\"param2\">1232131</param>" +
"</params>" +
"</msg>"
let url = URL(string:"<#URL#>")
var xmlRequest = URLRequest(url: url!)
xmlRequest.httpBody = stringParams.data(using: String.Encoding.utf8, allowLossyConversion: true)
xmlRequest.httpMethod = "POST"
xmlRequest.addValue("application/xml", forHTTPHeaderField: "Content-Type")
Alamofire.request(xmlRequest)
.responseData { (response) in
let stringResponse: String = String(data: response.data!, encoding: String.Encoding.utf8) as String!
debugPrint(stringResponse)
}
With Swift 3 and Alamofire 4 you would create a custom ParameterEncoding. As with any other XML encoded body, SOAP messages can use this parameter encoding as in the following example. Other XML body encodings can be created similarly (check the line where it says urlRequest.httpBody = ...):
struct SOAPEncoding: ParameterEncoding {
let service: String
let action: String
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("text/xml", forHTTPHeaderField: "Content-Type")
}
if urlRequest.value(forHTTPHeaderField: "SOAPACTION") == nil {
urlRequest.setValue("\(service)#\(action)", forHTTPHeaderField: "SOAPACTION")
}
let soapArguments = parameters.map({key, value in "<\(key)>\(value)</\(key)>"}).joined(separator: "")
let soapMessage =
"<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/' s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'>" +
"<s:Body>" +
"<u:\(action) xmlns:u='\(service)'>" +
soapArguments +
"</u:\(action)>" +
"</s:Body>" +
"</s:Envelope>"
urlRequest.httpBody = soapMessage.data(using: String.Encoding.utf8)
return urlRequest
}
}
And then use it like that:
Alamofire.request(url, method: .post, parameters: ["parameter" : "value"], encoding: SOAPEncoding(service: "service", action: "action"))
Assuming you that you're missing valid HTTP headers in your request, the updated request could look like:
Alamofire.request(.POST, "https://something.com", parameters: Dictionary() , encoding: .Custom({
(convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
let data = (self.testString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
mutableRequest.HTTPBody = data
mutableRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
return (mutableRequest, nil)
}))
.responseJSON { response in
print(response.response)
print(response.result)
}
}
So, basically you should add one line
mutableRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
Update:
Try same, but use responseData or responseString instead of responseJSON because it is possible that your response is not JSON

alamofire send request via soap

i use alamofire . before convert code to swift3 , everything was ok but after convert to swift3 when call my method ... data be empty .
getRequest return a NSMutableURLRequest :
private func getRequest(_ soapAction: String, urlService: URL, methodName: String, params: NSArray?) -> NSMutableURLRequest {
var newSoapMessage = ""
if let _ = params {
newSoapMessage = getSoapMessage(methodName, params: params!)
} else {
newSoapMessage = getSoapMessage(methodName)
}
request = NSMutableURLRequest(url: urlService)
lengthSoapMessage = String(newSoapMessage.characters.count)
request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue(lengthSoapMessage, forHTTPHeaderField: "Content-Length")
request.addValue("Basic \(accountBase64)", forHTTPHeaderField: "Authorization")
request.addValue(soapAction, forHTTPHeaderField: "SoapAction")
request.httpMethod = "POST"
request.httpBody = newSoapMessage.data(using: String.Encoding.utf8)
return request
}
now :
var request = getRequest(soapAction,urlService: Common.urlShatelService! as URL, methodName: methodName, params: params)
Alamofire.request(request as! URLRequestConvertible).responseData { response in
switch response.result {
case .success(let value):
let result = Result.success(value)
callBack(result)
break
case .failure:
let result = Result<Data>.failure
callBack(result)
print("exception: \(response.result.error)")
break
}
}
before convert , alamofire accept a request but after convert i must cast to URLRequestConvertible !!!!
now . when call alamofire return this exception :
2016-09-27 17:17:57.267619[3454:1060477] Could not cast value
of type 'NSMutableURLRequest' (0x101e445b8) to
'Alamofire.URLRequestConvertible' (0x101e400b0).
I had the same issue.
Try changing the type NSMutableURLRequest for URLRequest.
request = URLRequest(url: urlService)

iOS : http Post using swift

I figured it out solution at the bottom
I am trying to make an HTTP post request to my server. Here's what I did
var request : NSMutableURLRequest = NSMutableURLRequest(URL : NSURL(string : "myURL")
let session : NSURLSession = NSURLSession.sharedSession()
request.allHTTPHeaderFields = (headers as [NSObject : AnyObject])
request.HTTPShouldHandleCookies = true
request.HTTPMethod = "POST"
var postData = "frontend=iOS"
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
NSHTTPCookieStorage.sharedHTTPCookieStorage().cookieAcceptPolicy = NSHTTPCookieAcceptPolicy.Always
println(request.allHTTPHeaderFields)
println(request.HTTPBody)
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data)
println(json)
onCompletion(json, error)
})
task.resume()
this is not setting the HTTPRequest.POST
I tried printing the request to the server on the server side. IT said post was empty
POST : [QueryDict : {}]
What am I missing here? Any help is appreciated
Solution :
I mistakenly set the content-value to application/json when in fact it
was not a json body. Removing it solved the problem
use https://github.com/Alamofire/Alamofire
easy networking :)
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.response { (request, response, data, error) in
println(request)
println(response)
println(error)
}
you can use all of the below.
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs
var url = NSURL(string: urlstring)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
See How to escape the HTTP params in Swift on the way to correctly encode key-value pairs into the data string.

Resources