I'm trying to send a Integer value to WebService with body so I created a function like that :
static func GetRoomVersionAndRemainingSeconds(auctionId:Int,completed:#escaping (ServiceResultDene<String>)->()){
var memberJson : String = ""
do{
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(auctionId)
memberJson = String(data: jsonData, encoding: String.Encoding.utf8)!
}catch{
print(error)
}
var request = URLRequest(url: URL(string: WebServiceUrls.GetRoomVersionAndRemainingSeconds)!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(Util.cookie, forHTTPHeaderField: "Cookie")
request.httpBody = (memberJson).data(using: .unicode)
Alamofire.request(request).responseJSON{response in
....
}
When I try above code , it perfectly encode the Integer value on IOS 13+ -- memberJson is = "\"4\""
But when I try this on IOS 12.4 It doesnt encode and error.localizedDescription returns : invalidValue(4, Swift.EncodingError.Context(codingPath: [], debugDescription: "Top-level Int encoded as number JSON fragment.", underlyingError: nil))
What is the problem is here ? Any suggestion could be good.Thanks
The JSON encoding is pointless. In practice you are going to convert an Int to a String.
This can be done much simpler
static func GetRoomVersionAndRemainingSeconds(auctionId: Int,completed: #escaping (ServiceResultDene<String>)->()){
var request = URLRequest(url: URL(string: WebServiceUrls.GetRoomVersionAndRemainingSeconds)!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(Util.cookie, forHTTPHeaderField: "Cookie")
request.httpBody = Data(String(auctionId).utf8)
Alamofire.request(request).responseJSON{response in
....
}
By the way the reason of the error is that JSONEncoder doesn’t support to encode fragments prior to iOS 13.
Related
I hope you can help me.
I am currently using native swift apis for URLSession and URLRequest network calls.
I have achieved the correct sending of json structures with the use of dictionaries.
let params: [String: Any] = ["user": "demo"]
var request = URLRequest(url: URL(string: "https://.....")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
}catch _ {}
How would it be possible to send a simple string?
let params: "demo"
var request = URLRequest(url: URL(string: "https://.....")!)
request.httpMethod = "POST"
request.httpBody = .......?
You just need to convert the string to a Data, using data(using:):
request.httpBody = "a simple string".data(using: .utf8)
You can try
request.httpBody = Data("yourString".utf8)
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
I am trying to upload a string array to the Edamam API that uses the data from my local database. For the API, I need to post an array of strings with a label "ingr" so that it would recognize it. I should be able to enter the "\(mass) grams \(name)" of each ingredient and get a response that would analyze the macronutrients of said ingredient. The code I'm using:
API Config:
func getData(strURL: String, dictParam: Dictionary<String, Any>, completion: #escaping(Dictionary<String, AnyObject>)->()) {
var request = URLRequest(url: URL(string: strURL)!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: dictParam, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
print(response!)
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
print(json)
completion(json)
} catch {
print("error")
}
})
task.resume()
}
API call:
let dictParams = ["ingr":["100 grams apple"]] as Dictionary<String, Any>
APICalling.shared.getData(strURL: baseURL, dictParam: dictParams) { (response) in
action()
}
}
When using the Rested app, I can upload as many ingredients as I want and will get the correctly formatted response, everything is dandy. However, when I try to implement the code in my app, it prints "error":conflict. Any ideas how I can properly implement the API call?
Found a fix to the issue. Added some headers to my request, everything works fine now.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("*/*", forHTTPHeaderField: "Accept")
request.addValue("no-cache", forHTTPHeaderField: "Cache-Control")
request.addValue("api.edamam.com", forHTTPHeaderField: "Host")
request.addValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
request.addValue("keep-alive", forHTTPHeaderField: "Connection")
I'm sending this data to a server and I would like it to respond. Tried this code but it doesn't work.
let parameters = [ "imie" : (imie), "nazwisko" : (nazwisko), "telefon" : (telefon), "adres" : (adres), "miasto" : (miasto), "kod" : (kod), /*"powiat" : (powiat), "wojewodztwo" : (wojewodztwo),*/ "opis" : (selectedvalue) ]
let url = URL(string: "http://www.hetman.pl/post1.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.setBodyContent(parameters)
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
if error != nil{
return
}
do{
let t = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print(t as? String)
} catch{
print("Error 43 -> \(error)")
}
}
Request is correct and server is processing data properly, but response gives me this error:
Error 43 -> Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}
So the question is, how do I get the data back from server?
Please check if response from this url is JSON only. You might be getting XML or string response.
Try below line if you are getting String response :
let stringResponse = String(data: data!, encoding: String.Encoding.utf8) as String!
Try below line if you are getting XML response :
let xmlDictionary = try XMLSerialization.xmlObject(with: data!) as? [String: Any]
Why there is to content type?
// code 3840, data.length = 1 byte, so empty and no error
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
Remove first content-type header field and try with only:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
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)
}