Alamofire says "Invalid URL" when I add russian letters to the request [duplicate] - swift

My application is using an NSURL like this:
var url = NSURL(string: "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country=")
When I tried to make a task for getting data from this NSURL like this:
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error == nil {
var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)
println("urlContent \(urlContent!)")
} else {
println("error mode")
}
but I got error when trying to got data from that address, although when I using safari go to link: "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country=" I can see the data. How can I fix that?

Swift 2
let original = "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country="
if let encodedString = original.stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLFragmentAllowedCharacterSet()),
url = NSURL(string: encodedString)
{
print(url)
}
Encoded URL is now:
"http://www.geonames.org/search.html?q=A%C3%AFn+B%C3%A9%C3%AFda+Algeria&country="
and is compatible with NSURLSession.
Swift 3
let original = "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country="
if let encoded = original.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
let url = URL(string: encoded)
{
print(url)
}

Related

Swift, how can I return the data from HTTP request?

I have found learning swift to be more or less unbearable to do anything, something that would be done in a single line in Python becomes a whole task in swift.
I am trying to return the data from a http request and cannot find a single source that explains how. The only things I can find prints the data instead of returning it, either as a dictionary (from using JSONSerialization) or simply as a string.
let url = URL(string: "url")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("error: \(error)")
} else {
if let response = response as? HTTPURLResponse {
print("statusCode: \(response.statusCode)")
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("data: \(dataString)")
}
}
}
task.resume()
func makePostRequest(){
let urlPath: String = "http://www.swiftdeveloperblog.com/http-post-example- script/"
var url: NSURL = NSURL(string: urlPath)!
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
var stringPost="firstName=James&lastName=Bond" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval = 60
request.HTTPBody=data
request.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if (jsonResult != nil) {
// Success
println(jsonResult)
let message = jsonResult["Message"] as! NSString
println(message)
}else {
// Failed
println("Failed")
}
})
}

Get the HTML content when hitting URL in swift 3

My question is i want to hit the url and when i hit the url on server side the php return the results just echo in php and i have to save that result in variable in swift 3, i tried the below code:
let URLstr = URL(string: strURL)
let request = URLRequest(url: URLstr!)
request.httpMethod = "POST"
print (request)
I didn't get the content of URL in swift which is much easier in objective C.
Use the string initializer with the url.
do {
let contents = try String(contentsOf: URLstr, encoding: .ascii)
} catch {
// handle error
}
Or you can use URLSession.
let task = URLSession.shared.dataTask(with: URLStr) { data, response, error in
guard data != nil else { // no data }
let contents = String(data: data!, encoding: .ascii)
}
task.resume()
I adjusted the code provided above. To fetch HTML code use URLSession.
Swift 5
let session = URLSession.shared
let url = URL(string: "https://yourwebsiteaddress.com/")!
let task = session.dataTask(with: url) { data, response, error in
// Check whether data is not nil
guard let loadedData = data else { return }
// Load HTML code as string
let contents = String(data: loadedData, encoding: .utf8)
print(contents)
}
task.resume()

swift NSURL gets back an "unable to read data" message even with https://

I am trying to learn iOS following a course and they ask to do the following:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//var string1 = "http://www.google.com"
//var string1 = "https://www.weather-forecast.com/locations/San-Antonio/forecasts/latest"
//var url = NSURL(string: string1)
var url = NSURL(string: "https://google.com")
print(url)
if url != nil {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
var urlError = false
if error == nil {
var urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(urlContent)
} else {
urlError = true
}
if urlError == true {
self.showError()
}
})
task.resume()
} else {
showError()
}
}
the app doesn't show any web page content and when debugging I find that the object for the url says that it is "unable to read data"
I have tried with http and https. I have tried with different web sites.
I have tried the address in the safari of the simulator and it loads.
Can someone tell me why is this not working
Thanks in advance.
gariva
You're using wrong encoding. The webpage you're trying to fetch (http://www.google.com/) uses ISO-8859-1.
I was able to reproduce your issue. Fetch worked when I changed encoding. Try this:
var urlContent = NSString(data: data!, encoding: NSISOLatin1StringEncoding)
For display web page you should use UIWebView element. Something like this:
let url = NSURL(string: "https://google.com")
let webView = UIWebView(frame: self.view.frame)
self.view.addSubview(webView)
webView.loadRequest(NSURLRequest(URL: url!))

How to use special character in NSURL?

My application is using an NSURL like this:
var url = NSURL(string: "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country=")
When I tried to make a task for getting data from this NSURL like this:
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error == nil {
var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)
println("urlContent \(urlContent!)")
} else {
println("error mode")
}
but I got error when trying to got data from that address, although when I using safari go to link: "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country=" I can see the data. How can I fix that?
Swift 2
let original = "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country="
if let encodedString = original.stringByAddingPercentEncodingWithAllowedCharacters(
NSCharacterSet.URLFragmentAllowedCharacterSet()),
url = NSURL(string: encodedString)
{
print(url)
}
Encoded URL is now:
"http://www.geonames.org/search.html?q=A%C3%AFn+B%C3%A9%C3%AFda+Algeria&country="
and is compatible with NSURLSession.
Swift 3
let original = "http://www.geonames.org/search.html?q=Aïn+Béïda+Algeria&country="
if let encoded = original.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
let url = URL(string: encoded)
{
print(url)
}

Getting the JSON data from cloudant

I have a database created in Cloudant and I am trying to parse that data in my Swift project. I have imported the Cloudant libraries, but I am not able to parse the data.
Here is the code that I Have been using till now
var url = "https://username:password#cloudant.com/dashboard.html#/database/db_2/login_details"
var request = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if jsonResult != nil {
if let item = json[0] {
if let student_name = item["Student_name"] {
if let pasword = student_name["password"] {
println("Login Successfull")
}
}
}
}
}
Can somebody tell me where am I going wrong?
You should use stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) to convert any special characters your link may have. Also NSURL may return nil so you need to use if let to handle it as follow :
if let link = "https://username:password#cloudant.com/dashboard.html#/database/db_2/login_details".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
if let checkedUrl = NSURL(string: link) {
println("valid Url")
// your code
} else {
println("invalid Url")
}
}