I need to create an object of NSURL from url string like this. It contains | symbol. The problem is that NSURL constructor always returns nil, because of | symbol. How can I create this object?
I think it is lowercase l, not the pipe | character.
However, you can use stringByAddingPercentEncodingWithAllowedCharacters: with NSCharacterSet.URLQueryAllowedCharacterSet() to escape invalid characters in the URL:
url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
--
let url = "https://static-maps.yandex.ru/1.x/?l=map&pt=55,1583062965,61,3948104504,pm2rdm&size=600,300"
let escapedURL = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
print(NSURL(string: escapedURL))
Related
I request you to give me a solution where the result of NSString and String both are same
downloadedFile = MOM'&^*%s-HC.pdf (In NSString)
let path = pathComponent.appendingPathComponent(downloadedFile as String)
print(path) //OutPut: ttt_gmail_com/MOM'&%5E*%25s-HC-2.pdf
If I test with regular expression result is OK.
let NSStringValue = "MOM'&^*%s-HC.pdf" as NSString
print(NSStringValue) // Output: MOM'&^*%s-HC.pdf
let StringValue = downloadedFile as String
print(StringValue) // Output: MOM'&^*%s-HC.pdf
but while I put that code in appendingPathComponent it changes my result.
You have a file name which has all the special characters here, I tried your case in a sample project trying to load such file in UIDocumentInteractionController and it seems when I have a file name with special character in my document directory and i try to retrieve it, few special characters are URL encoded.
Observe the file name I used here is "MOM'&^*%s-HC.pdf" and saved it in the doc directory but when I retrieve it from the document directory using the following code few characters are URL encoded as I am fetching the path as URL.
So this means that your original file name
MOM'&^*%s-HC.pdf
is now alterated and replaced by percentage escape sequence strings,
MOM'&%5E*%25s-HC.pdf
observe the below code which I used
var pdfURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
pdfURL = pdfURL.appendingPathComponent(fileName)
To resolve this all i did was removed the percentage escape sequence when I am creating the URL and it worked I was able to view the PDF in the UIDocumentInteractionController
fileName.removingPercentEncoding!
Hope it helps.
Currently i am using the following way to encode the url
urlAndMethod.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
After encoding
http://103.50.154.52:8383/api/master/insta-list?category=Postpaid%20Mobile%20CDMA%20&%20Landline
How do i handle the special characters including '&'
You can use .urlHostAllowed characterset.
let escapedString = someString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
The goal is to serialize a Swift object by converting it to a JSON object then converting the JSON object into a JSON string that can be passed over the wire and decoded on the other side.
The problem is producing a valid JSON string.
Newlines must be escaped in a JSON string, but Swift interprets special characters in the escaped string instead of treating the string as a literal.
For example:
let a = "foobar\nhello\nworld"
let escapedString = a.replacingOccurrences(of: "\n", with: "\\n")
print(escapedString)
What gets printed is foobar\nhello\nworld instead of the desired foobar\\nhello\\nworld.
How do you tell Swift to treat a string as a literal and not to interpret special characters within?
UPDATE
As OOPer points out, using debugPrint shows the \\n characters remaining intact.
However, when paired with evaluateJavaScript in WKWebView, the \\n characters are turned into \n, which is the root issue. For example:
let script = "\(callback)(\'\(escapedString)\')"
webView!.evaluateJavaScript(script) { (object: Any?, error: Error?) -> Void in
print("Done invoking \(callback)")
}
There is no unescaped string syntax like in javascript template literals which is probably what you are looking for; maybe they will add it in the future. Unfortunately you therefore have to escape each back slash which sometimes looks very scray, as in your example.
//This is the same as `foobar\nhello\nworld` where each char is a literal
let a = "foobar\\nhello\\nworld"
let escapedString = a.replacingOccurrences(of: "\\n", with: "\\\\n")
//This outputs `foobar\\nhello\\nworld`
print(escapedString)
Maybe you are just mistaking to interpret the output from print.
When you get foobar\nhello\nworld from print(escapedString), escapedString contains 20 characters -- f o o b a r \ n h e l l o \ n w o r l d.
This is a valid JSON string when enclosed between "s.
If you want to check the escaped result in String-literal-like notation, you can use debugPrint:
let a = "foobar\nhello\nworld"
let escapedString = a.replacingOccurrences(of: "\n", with: "\\n")
print(escapedString) //->foobar\nhello\nworld
debugPrint(escapedString) //->"foobar\\nhello\\nworld"
For UPDATE
When using with evaluateJavaScript, you'd better think what is the right code as JavaScript, if you want to represent a JSON escaped string in JavaScript, you would write in .js file (or in <script>...</script>):
someFunc('foobar\\nhello\\nworld');
So, you may need to write something like this:
let a = "foobar\nhello\nworld"
let escapedForJSON = a.replacingOccurrences(of: "\n", with: "\\n")
//In actual code, you may need a little more...
let escapedForJavaScriptString = escapedForJSON.replacingOccurrences(of: "\\", with: "\\\\")
let script = "\(callback)(\'\(escapedForJavaScriptString)\')"
webView!.evaluateJavaScript(script) { (object: Any?, error: Error?) -> Void in
print("Done invoking \(callback)")
}
What I am doing is shipping a JSON structured string on NSULRRequest, getting rid of the urlscheme prefix, serialize it to JSON and then whatever I can do with it.
urlscheme://{"Type":"photo","Name":"Photo13"}
So I changed NSURLRequest to string by doing
let url = request.URL
let string = "\(url)"
print(string)
but the string appears like
urlscheme://%7B%22Type%22:%22photo%22,%22Name%22:%22Photo13%22%7D
So I have to change it by invoking stringByReplacingOccurrencesOfString over and over on all possible changes.
replacedString = replacedString.stringByReplacingOccurrencesOfString("%7B",
withString: "{",
options: NSStringCompareOptions.LiteralSearch,
range: nil)
.
..
...
Is there a better way to do this in Swift?
What you've got there is a percent encode string. This is done because certain characters have special meanings within a URL. The NSString method stringByRemovingPercentEncoding will convert a percent encode string back to a normal string for you.
See this answer
I use obj-c and swift classes together. And at one swift class, I try to convert objective c code to swift. However, I have a problem about NSURL.
the original code is:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#://", appItem.URLSchema]];
and URLSchema is declared in the header file like this:
#property (nonatomic, copy) NSString *URLSchema;
I convert the objective c code which is above to swift:
var url: NSURL = NSURL(string:"%#://",relativeToURL: appItem.URLSchema)
but it says "missing argument for parameter "path" in call"
when I try this:
var url: NSURL = NSURL.URLWithString("%#://", appItem.URLSchema)
it says extra argument in call.
what do you suggest to convert it properly?
The second argument : RelativeToURL has the type NSURL and you pass a String
Try this :
var url:NSURL = NSURL(string: "\(appItem.URLSchema)://")
For more informations, you can take a look on the 'String Interpolation' section in the "Swift programming langage" iBook.
String interpolation is a way to construct a new String value from a
mix of constants, variables, literals, and expressions by including
their values inside a string literal. Each item that you insert into
the string literal is wrapped in a pair of parentheses, prefixed by a
backslash