I'm learning swift and I need to make a GET request, so this is my code:
var j = ["user": "xxxxxx#xxxxxx.xxx"]
var e: NSError?
let jsonData = NSJSONSerialization.dataWithJSONObject(j,options: NSJSONWritingOptions(0),error: &e)
var jsonString = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)
var urlPath = "http://test.example.io/materials?query=\(jsonString)";
println(urlPath)
var url: NSURL = NSURL(string: urlPath)
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.addValue("xxxxxxxxxxxxxxxxxxxx" , forHTTPHeaderField: "Teech-Application-Id")
request.addValue("xxxxxxxxxxxxxxxxxxxx" , forHTTPHeaderField: "Teech-REST-API-Key")
request.addValue("application/json" , forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "GET"
println(request)
And this is my output debug
http://test.example.io/materials?query={"user":"xxxxxxxxx#xxxxxxxxx.xxxxx"}
<NSMutableURLRequest: 0x7f8ee3480320> { URL: (null), headers: {
"Content-Type" = "application/json";
"Teech-Application-Id" = xxxxxxxxxxxxxxxxxxxxxxxx;
"Teech-REST-API-Key" = xxxxxxxxxxxxxxxxxxxxxxxxx;
} }
Why the first print function return the correct url and inside the print request there is a null url, where is my mistake ? I've tried with a url without a json and it runs.
I done it, the solution is escaping the string.
var escapedSearchTerm = urlPath.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
var url: NSURL = NSURL(string: escapedSearchTerm!)
Related
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 want to get error status code when my WebView is loaded.
When I open the connexion I use this code :
let simpler = "http://www.example.com"
let url = NSURL(string: simpler)
let request = NSURLRequest(URL: url!)
webview.loadRequest(request)
I have found this code but I obtain errors so it's not working :
Check URL of Loaded WebView
I want to get the errors in the ViewDidLoad
Try this one :-
var url:NSURL = NSURL(string: "http://www.example.com")!
var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
var postLength:NSString = String( postData.length )
var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
//request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("*/*", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
How to pass json as parameter string. I have tried by passing json as below but it throws error like AuthenticateUser: Invalid JSON primitive.
let jsonString = "{\"user\":\"usr\",\"password\":\"pass\"}"
var urlStr = "http://testserver/AuthenticateUser?data=\(jsonString)"
var url = NSURL(string: urlStr)
let request = NSMutableURLRequest(URL: url!)
request.URL = url
request.HTTPMethod = "POST"
request.addValue("application/xml", forHTTPHeaderField: "Content-Type")
request.addValue("application/xml", forHTTPHeaderField: "Accept")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
(data, response, error) in
var error: NSError?
if data != nil {
var reply = NSString(data: data!, encoding: NSUTF8StringEncoding)
println("reply >> \(reply)")
}
}
task.resume()
Add this line after request initializtion:
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(jsonString, options: nil, error: &err)
Update these lines for json format:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
Reference:
POST with swift and API
http://jamesonquave.com/blog/making-a-post-request-in-swift/
I brought you answer up to passing json parameter as a string to URL.
var jsonString = "{\"user\":\"usr\",\"password\":\"pass\"}"
if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
{
var error: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? NSDictionary
if error != nil
{
println(error)
}
else
{
println(json)
}
var strUser = json?.valueForKey("user") as String
var strPassword = json?.valueForKey("password") as String
println(strUser)
println(strPassword)
var url = "http://testserver/AuthenticateUser?data="
var urlUserParameter = "user="
var urlPasswordParameter = "&password="
var appendString = "\(url)\(urlUserParameter)\(strUser)\(urlPasswordParameter)\(strPassword)"
//OR
var appendStringOne = url + urlUserParameter + strUser + urlPasswordParameter + strPassword
println(appendString)
println(appendStringOne)
}
Explanation
I converted JSON string to NSDictionary.
Then i get value using key
Finally i append all these string and now we have URL with parameters.
I am new in swift language. I looked at some questions for parsing Json in swift in here but my issue is alittle different from others.
when i write /cmd=login¶ms{'user':'username','password':'pass'} it returns correct data. how to resolve this in swift
I send username and password to url as json but
it retrieve error which means "invalid format "
Please help me.
Here is what i have tried:
var url:NSURL = NSURL(string: "http://<host>?cmd=login")!
//var session = NSURLSession.sharedSession()
var responseError: NSError?
var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
// var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
var response: NSURLResponse?
request.HTTPMethod = "POST"
let jsonString = "params={\"user\":\"username\",\"password\":\"pass\"}"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:true)
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)
// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(httpResponse.statusCode)")
} else {
println("No HTTP response")
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("****response= \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("**** response =\(responseString)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers , error: &err) as? NSDictionary
}
task.resume()
Assuming based on your question that the format the server is expecting is something like this:
http://<host>?cmd=login¶ms=<JSON object>
You would need to first URL-encode the JSON object before appending it to the query string to eliminate any illegal characters.
You can do something like this:
let jsonString = "{\"user\":\"username\",\"password\":\"pass\"}"
let urlEncoadedJson = jsonString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url = NSURL(string:"http://<host>?cmd=login¶ms=\(urlEncoadedJson)")
Let's say url is
https://example.com/example.php?Name=abc&data={"class":"625","subject":"english"}
in Swift 4
let abc = "abc"
let class = "625"
let subject = "english"
let baseurl = "https://example.com/example.php?"
let myurlwithparams = "Name=\(abc)" + "&data=" +
"{\"class\":\"\(class)\",\"subject\":\"\(subject)\"}"
let encoded =
myurlwithparams.addingPercentEncoding(withAllowedCharacters:
.urlFragmentAllowed)
let encodedurl = URL(string: encoded!)
var request = URLRequest(url: encodedurl!)
request.httpMethod = "GET"
I don't think you need to encode your JSON the way you're doing it. Below should work.
let jsonString = "params={\"user\":\"username\",\"password\":\"pass\"}"
var url:NSURL = NSURL(string: "http://<host>?cmd=login&?\(jsonString)")!
//var session = NSURLSession.sharedSession()
var responseError: NSError?
var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
// var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
var response: NSURLResponse?
request.HTTPMethod = "POST"
You json string is not valid, it should be like:
let jsonString = "{\"user\":\"username\",\"password\":\"pass\"}"
As for the request, I think GET it what you really need:
var urlString = "http://<host>" // Only the host
let payload = "?cmd=login¶ms=" + jsonString // params goes here
urlString += payload
var url:NSURL = NSURL(string: urlString)!
// ...
request.HTTPMethod = "GET"
I'm (trying to) learn the Swift's Apple language. I'm at Playground and using Xcode 6 Beta. I'm trying to do a simple JSON Post to a local NodeJS server. I already had googled about it and the major tutorials explain how to do it in a project, not at PLAYGROUND, than don't write stupid thinks like: "google it" or "it's obvious" or "look this link" or never-tested-and-not-functional-code
This is what i'm trying:
var request = NSURLRequest(URL: NSURL(string: "http://localhost:3000"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response : NSURLResponse?
var error : NSError?
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
I had tried:
var dataString = "some data"
var request = NSMutableURLRequest(URL: NSURL(string: "http://posttestserver.com/post.php"))
request.HTTPMethod = "POST"
let data = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
var requestBodyData: NSData = data
request.HTTPBody = requestBodyData
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: false)
println("sending request...")
connection.start()
Thank you! :)
Nate's answer was great but I had to change the request.setvalue for it to work on my server
// create the request & response
var request = NSMutableURLRequest(URL: NSURL(string: "http://requestb.in/1ema2pl1"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response: NSURLResponse?
var error: NSError?
// create some JSON data and configure the request
let jsonString = "json=[{\"str\":\"Hello\",\"num\":1},{\"str\":\"Goodbye\",\"num\":99}]"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(httpResponse.statusCode)")
} else {
println("No HTTP response")
}
It looks like you have all the right pieces, just not in quite the right order:
// create the request & response
var request = NSMutableURLRequest(URL: NSURL(string: "http://requestb.in/1ema2pl1"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response: NSURLResponse?
var error: NSError?
// create some JSON data and configure the request
let jsonString = "json=[{\"str\":\"Hello\",\"num\":1},{\"str\":\"Goodbye\",\"num\":99}]"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(httpResponse.statusCode)")
} else {
println("No HTTP response")
}
Here is a little different approach using asynchronous request. You can use synchronous approach this way too but since everyone above used synchronous request, I thought show asynchronous request instead. Another thing is it seems cleaner and easier this way.
let JSONObject: [String : AnyObject] = [
"name" : name,
"address" : address,
"phone": phoneNumber
]
if NSJSONSerialization.isValidJSONObject(JSONObject) {
var request: NSMutableURLRequest = NSMutableURLRequest()
let url = "http://tendinsights.com/user"
var err: NSError?
request.URL = NSURL(string: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(JSONObject, options: NSJSONWritingOptions(rawValue:0), error: &err)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {(response, data, error) -> Void in
if error != nil {
println("error")
} else {
println(response)
}
}
}