This question already has answers here:
Swift - encode URL
(19 answers)
Closed 5 years ago.
I tried to call a custom url using this code below:
let myurl = "https://myserver.com/call?a|b|c"
let converted = URL(string: myurl)
print(converted)
But what I'm getting as result in converted is just "nil".
I'm pretty sure this is because of the wrong characters set in relation to the URL() class.
After some research all I got so far is this outdated Swift code:
var myurl = "https://myserver.com/call?a|b|c"
var newurl = myurl.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
print(newurl)
But it doesn't seems working this way.
How can I achieve to avoid the "nil" result using (in my case) Swift 4?
Found the solution on my own:
let myurl = "https://myserver.com/call?a|b|c"
let converted = URL(string: myurl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
print(converted!)
The new function is called addingPercentEncoding & I have to call it with the urlQueryAllowed property.
The urlQueryAllowed charset adds some characters like this to the url encoding: "!*'();:#&=+$,/?%#[]|"
VoliĆ !
Related
This question already has an answer here:
Xcode 8.2.1 / Swift 3 - Load TableView from Plist Array of Dictionaries
(1 answer)
Closed 5 years ago.
early this month i started learning swift as i found it fun and easier than obj-c
i came up with an idea trying to show english words and meaning on my language,
for that case i have a plist ready on my hand and a UITableViewController
with 2 Labels
here is my plist
so on my UITableViewController, i tried to get hands on the plist file with this code
let path = NSBundle.mainBundle().pathForResource("TableData", ofType: "plist")
let array = Array(contentsOfFile: path!)
and i got stuck on the rest
thanks
If you are just staring to learn Swift please start with Swift 3. Your Swift 2 code is outdated.
The recommended way to load a property list file is PropertyListSerialization
let url = Bundle.main.url(forResource: "TableData", withExtension: "plist")!
do {
let data = try Data(contentsOf: url)
let dataArray = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[String:String]]
print(dataArray)
} catch {
print("This error must not happen", error)
}
I have x 2 questions about urls and webViews.
Question 1:
I have a string which I am getting from an API that is supposed to be a url. The string is https://godochurch.blob.core.windows.net/sermons/1031/30-1-2017-Vision Sunday-Devotion.mp3
When trying to convert to a url I'm getting nil.
Here is the code:
if let sermonUrl = sermonUrl {
if let url = URL(string: sermonUrl) {
let requestObj = URLRequest(url: url)
webView.loadRequest(requestObj)
}
}
I have worked out that the space between 'Vision' and 'Sunday' is the problem.
Should I be encoding the string in some way before trying to convert it to a URL? What's confusing is that if I paste the string into my browser it works just fine, but I notice the browser is percent encoding the space.
If I am supposed to be encoding the string, how do I do that?
Question 2:
I see that URL(string: "urlStringHere") is only available from iOS 10. My app needs to work for iOS 9. How can I convert the above code so it works on iOS 9 and 10.
Thanks in advance for your time.
1: escape that space with %20 or +:
if let url = URL(string: "https://godochurch.blob.core.windows.net/sermons/1031/30-1-2017-Vision%20Sunday-Devotion.mp3") {
// ...
}
2: URL was introduced with Swift 3, which is compatible with iOS 8 and later. See this question on how to make it work with older versions of iOS.
Edit: the easiest way to percent-escape a URL is to use URLComponents:
var components = URLComponents(string: "https://godochurch.blob.core.windows.net")!
components.path = "/sermons/1031/30-1-2017-Vision Sunday-Devotion.mp3"
if let url = components.url {
// ...
}
If you happen to get you URL strings from a webservice and it contains a space, that service is bad. Space is not allowed in an URL. Web browsers relax that rule because they know there are bad URLs out there. Swift won't take it.
So I have a url like this:
let remoetURL = "http://xxx-test.img-cn-hangzhou.aliyuncs.com/materials/talk_-XXXXX-XXXXXXX/STEM RULE.pdf"
As you can see, at then end of the url, there is a white space, so I need to get rid of it to have a valid encoded url.
After doing some research, I realized I might use
let escapedString = remoteURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())
But this does not returned the expected working url, because it encodes the ":" after "http" too
http%3A//xiaobandeng-staging.img-cn-hangzhou.aliyuncs.com/talk_materials/talk_-K4yjX4-238Ku74WVIJk/STEM%20RULE.pdf
I have also tried URLHostAllowedCharacterSet, but no luck. So I wonder if it is because I don't have www here, so it does not recognise which part is the host correctly. If so, what might be the elegant solution? I know I could replace white spaces with %20 by calling stringByReplacingOccurrencesOfString, but that seems just a bit fragile.
Thank you in advance.
Try this used by SwiftyJSON
let urlString = remoteURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
Swift 3:
let urlString = remoteURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
Have you try this
let urlPath = NSString(format: remoetURL).stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
For iOS 9
let encodedHost = NSString(format: remoetURL).stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())
Hope this will help you
I'm getting this error in latest version of xcode using swift 2
on line
let s = linkTxt.text
Text in linkTxt appears by button "pasteFromClipBoard"
let s = linkTxt.text
let u = NSURL(string: s!)
let file = u?.lastPathComponent
What is the reason of it and how to fix it?
Update:
the problem appears in function saveData() which calls when file downloading is finished. It calls from NSURLSessionDataTask function. More interesting, that in start-downloading-button there are the same lines where filename is generating and there is no such error on it. I fixed these issues by declaring variables, writing text's values into them and use these variables in saveData() except textObject.text; I had to delete lines with NSUserDefaults from saveData() too because I got the same error. Did understand nothing >_<
Update 2:
It's really a bug. I've deleted this line and wrote again - problem fixed
linkTxt.txt is returning nil and NSURL(string: s!) will try to forcefully unwrap it.
let s = linkTxt.text
if let s = linkTxt.txt {
let u = NSURL(string: s!)
let file = u?.lastPathComponent
}
Hi I am really new to coding in Swift, and am trying to follow the codes in this book: http://www.apress.com/9781484202098. Learn iOS 8 App Development 2nd Edition by James Bucanek
In particular, I am working through Chapter 3 - building a URL shortening app, but despite having copied the code exactly, I am getting an error on the code in Page 76:
if let toShorten = webView.request.URL.absoluteString {
which states 'NSURLRequest?' does not have a member named 'URL'.
I have tried googling an answer, but unfortunately have not come across anything. Any response I can find seems to suggest that my code ought to be working (e.g. How to get url which I hit on UIWebView?). This seems to have the closest answer SWIFT: Why I can't get the current URL loaded in UIWebView? but the solution does not appear to work for me. If I add a ? after the request, it will then at least build it, but I then have a nil variable returned.
I am using Xcode v6.1.1. Here is the piece of code that is coming up with the error in ViewController.swift:
let GoDaddyAccountKey = "0123456789abcdef0123456789abcdef" //this is replaced by my actual account key in my own code
var shortenURLConnection: NSURLConnection?
var shortURLData: NSMutableData?
#IBAction func shortenURL( AnyObject ) {
if let toShorten = webView.request?.URL.absoluteString { // ? now added
let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
shortURLData = NSMutableData()
if let firstrequest = NSURL(string: urlString) //added if here and removed !
let request = NSURLRequest(URL:firstrequest)
shortenURLConnection = NSURLConnection(request:request, delegate:self)
shortenButton.enabled = false
}
}
}
If you have any suggestions on how I can fix this, I would really appreciate it!
Update:
Following suggestions from Ashley below, I have amended my code so that it is no longer bringing up the error (see comments above). However, it is now no longer running. This appears to be because the urlString is being created as http://api.x.co/Squeeze.svc/text/d558979bb9b84eddb76d8c8dd9740ce3?url=Optional("http://www.apple.com/"). The problem is therefore the Optional() that is included and thus makes it an invalid URL. Does anyone have a suggestion on how to remove this please?
request is an optional property on UIWebView:
var request: NSURLRequest? { get }
also stringByAddingPercentEscapesUsingEncoding returns an optional:
func stringByAddingPercentEscapesUsingEncoding(_ encoding: UInt) -> String?
What you need is to make user of optional binding in a few places:
if let toShorten = webView.request?.URL.absoluteString {
if let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
shortURLData = NSMutableData()
if let firstrequest = NSURL(string: urlString) { // If a method can return a nil, don't force unwrap it
let request = NSURLRequest(URL:first request)
shortenURLConnection = NSURLConnection(request:request, delegate:self)
shortenButton.enabled = false
}
}
}
See Apple's docs on optional chaining for details
See Apple's docs for NSURL class