Swift 5: simple string URLRequest - ios

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)

Related

How to pass two or many values in WKWebView's HTTP request body?

I want to pass two values in HTTP request body. I try to do it like this but it isn't working. can anyone help me?
guard let url = URL(string: "*****") else { return }
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let post: String = "cardId=\(viewModel.getCardId())&requestId=\(viewModel.getRequestId())"
if let postData: Data = post.data(using: String.Encoding.ascii, allowLossyConversion: true) {
request.httpBody = postData
webView.load(request as URLRequest)
}

JSONEncoder doesnt work integer values below IOS 13-

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.

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

Swift 2 JSON POST request [dictionary vs. String for HTTPBody of NSMutableURLRequest]

I have the following swift code that submits a POST request successfully.
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.HTTPBody = "foo=bar&baz=lee".dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request, completionHandler: completionHandler)
Instead of using query parameter like syntax, I'd like to use a dictionary, but when I do the following:
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(["foo":"bar", "lee":"baz"], options: [])
let task = session.dataTaskWithRequest(request, completionHandler: completionHandler)
(like what I've seen around), it seems to submits the request as if the body is empty.
My main question is: how do these syntaxes differ, and how do the resulting requests differ?
NOTE: Coming from JS, I'm testing the endpoint in a javascript environment (jquery.com's console) like the following, and it's working successfully:
$.ajax({
url: url,
method: 'POST',
data: {
foo: 'bar',
baz: 'lee'
}
});
What #mrkbxt said. It's not a matter of how the syntax differs, but a matter of the different data types your sending with your request. UTF8 string encoded text is the default value for NSMutableURLRequest content type, which is why your first request works. To use a JSON in the body you have to switch the content type to use JSON.
Add the following to your request object so it accepts JSON:
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
For a content-Type of type "x-www-form-urlencoded" you can do the following.
let bodyParameter = ["foo":"bar", "lee":"baz"]
let bodyString = bodyData.map { "\($0)=\($1)" }.joined(separator: "&")
let encodedData = NSMutableData(data: bodyString.data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.HTTPBody
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = session.dataTaskWithRequest(request, completionHandler: completionHandler)
This will take your dictionary, tranform it into a string that conforms to the content-Type of your request (by joining the dictionary using a separator) and then encoding it using utf8.

Resources