whitespace in url - alamofire - swift

I'm trying to post a http request using alamofire. my request is as follows:
let url = "\(myBaseURL)/{name:adriana lima}"
Alamofire.request(url.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!, method: .post)
I tried some encoding types such as :
urlFragmentAllowed , whitespaces
but they're not working.
I know if i use parameters, whitespace would be handled but in this case, i have to pass parameters inside of url. but it results error. how can i post this and how should i encode it ?

You need to encode the URL before passing it to alamofire method. using addingPercentEncoding.
let urlString = "\(myBaseURL)/{name:adriana lima}"
guard let encodedURL = urlString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else {
//Invalid URL
return
}

Related

contentsof:url loads url content of a truncated URL

When I use contentsof:url it truncates the url before retrieving the content, resulting in different html content than the displayed in the WKWebView.
For example
contents = try String(contentsOf: https://www.amazon.com/gp/aw/d/B00BECJ4R8/ref=mp_s_a_1_1?ie=UTF8&qid=1531620716&sr=8-1-spons&pi=AC_SX236_SY340_QL65&keywords=cole+haan&psc=1)
returns the contents of this page: https://www.amazon.com/gp/aw/d/B00BECJ4R8/
Why is this happening? Is there an alternative method that allow you to read the content of the actual URL not the truncated URL?
Any advice if very much appreciated.
Thank you.
You shouldn't be using String(contentsOf:) to load a website. You should use the URL Loading System for this work then passing that object back to your webView.load(_:) method in viewDidLoad()
let urlString = "https://www.amazon.com/dp/B00BECJ4R8/?tag=stackoverflow17-20"
// URL construct may fail in case of the String not being a properly formatted URL, so unwrap it.
if let url = URL(string: urlString) {
// Create a URLRequest instance with the new url.
let request = URLRequest(url: url)
// Load the request.
webView.load(request)
}

URL constructor doesn't work with some characters

I'm trying to call a php-script from my app using URLRequest.
The Url path is generated in the String-Variable query and for the request I convert it like this
guard let url = URL(string: query) else {
print("error")
return
}
usually it works, but when the request contains characters like ä, ö, ü, ß the error is triggered. How can I make it work?
The URL(string:) initializer doesn't take care of encoding the String to be a valid URL String, it assumes that the String is already encoded to only contain characters that are valid in a URL. Hence, you have to do the encoding if your String contains non-valid URL characters. You can achieve this by calling String.addingPercentEncoding(withAllowedCharacters:).
let unencodedUrlString = "áűáeqw"
guard let encodedUrlString = unencodedUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: encodedUrlString) else { return }
You can change the CharacterSet depending on what part of your URL contains the characters that need encoding, I just used urlQueryAllowed for presentation purposes.
Split your URL in two separate parts:
let baseURLString = "https://www.example.com"
let pathComponent = "áűáeqw"
let fullURL = URL(string: baseURLString)?.appendingPathComponent(pathComponent)

Swift 4 using URLSession with non-secure URL

I'm trying to send data to a WebAPI service that uses HTTP and not HTTPS, however I get the following error:
"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
Here is my code:
func logSample(emailSKU:String) -> String {
//let myAPI = "https://itunes.apple.com/us/rss/topmovies/limit=25/json"
let myAPI = "http://<myURlHere>/api/xxx"
let url = URL(string: myAPI)
let session = URLSession.shared.dataTask(with: (url)!) { (data, response, error) in <====== Breaks on this line
print("Response was:")
print(response)
}
session.resume()
return "return something here"
}
The API service works just fine from other applications.
If I use the iTunes url above, then everything works fine, so the only difference is the HTTP ver HTTPS.
I have added 'Allow Arbitrary Loads' declaration to the plist, any ideas?
I checked the RFC 3986 and it is the "|" character that isn't allowed and that you need to encode.
To supplement #Joakims answer:
The URL given is invalid because of the use of the | character and needs to be encoded. You can do this in the following way:
let urlString = "http://example.com/api/Scans?emailSKU=fred#example.com|123456"
if let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
let url = URL(string: encodedURLString)
print(url)
}
Which outputs:
Optional(http://example.com/api/Scans?emailSKU=fred#example.com%7C123456)
So | needs to be encoded, which replaces it with %7C

How to make an HTTP GET Request with Parameters. SwiftyJSON Swift

Below mentioned snippet is working just fine. It queries JSON data. I just want to know how can I pass parameters with this.
let filePath = NSURL(string: "http://localhost:2403/postedjob")
let jsonData = NSData(contentsOfURL:filePath!)
let json = JSON(data: jsonData!, options: NSJSONReadingOptions.AllowFragments, error: nil)
I want to pass this parameters:
let params = ["$limit": 2, "$sort": ["id":"+1"]] as Dictionary<String, AnyObject>
Alamofire may be a good option for you to pass the parameters.
https://github.com/Alamofire/Alamofire
For a GET request pass parameters in the query string (the part after the "?" mark).
For a POST request parameters can be sent in the body in a number of ways. Raw data, form data and JSON among other methods.
Of course the server has to match the method used.

making a url Request ending with an %-Sign

My url Request is like "http://www.heriam.com/gms.setvalue%20dim100%"
and i use Alamofire for the Request
Tha APP chrashed with fatal error: unexpextendly found nil while unwrapping an Optional Value
Alamofire.request(.GET, "http://www.heriam.com/gms.setvalue%20dim100%")
.authenticate(usingCredential: credential)
.response {(request, response,string, error) in
println(response)
}
The problem is the last %! If i leave it all is fine an the Request works.
do you have an idea sending a Request ending with an %???
You have to prepare your link before converting it to url using stringByAddingPercentEscapesUsingEncoding. Besides that NSURL method might return nil so you should use if let to unwrap the optional result as follow:
let link = "http://www.heriam.com/gms.setvalue%20dim100%"
if let linkWithPercentEscape = link.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
if let url = NSURL(string: linkWithPercentEscape) {
println(url)
}
}