Find a string value on a webpage with swift - swift

I want to pull the balance value from a website: https://nimiq.watch/#NQ74+FLQL+DRE3+99PF+CET0+3N7D+JKLF+MQP6+87KS
The number after hash is the wallet address
I tried to use this to find the balance
wallet_address = "NQ48+8CKH+BA24+2VR3+N249+N8MN+J5XX+74DB+5XJ8"
let myURLString = "https://nimiq.watch/#"+wallet_address
let myURL = NSURL(string: myURLString)
var myHTMLString = try String(contentsOf: myURL! as URL)
print(myHTMLString)
when I inspect element in browser it shows this..
<span>340510.29275 NIM</span>
But when I pull with the script I get this
<span>{%=_formatBalance(Nimiq.Policy.satoshisToCoins(o.balance))%} NIM</span>
any suggestions? or is this just not possible.. thanks!

Related

SwiftAudio - Open filename which contains whitespaces

I'm using SwiftAudio library to open local url but I have a problem when I try to open an url that contains whitespaces in filename.
So, for example, if I try to open a file which name is "example_file.mp3" this audio is successfully opened.
But, if I try to open a file which name is "example file.mp3" an error occurs: "The requested URL was not found on this server".
I've also tried to replace the name with "example%20file.mp3" but I have the same error.
I wrote this code:
var urlPath = "/Users/manuela/Library/Developer/CoreSimulator/Devices/64E0D907-16AD-41A9-9667-4B3C701D4F1B/data/Containers/Data/Application/488A8AAD-EF4B-452D-9A8A-67307C489C72/Library/example file.mp3"
urlPath = urlPath.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
print(urlPath) // this prints "/Users/manuela/Library/Developer/CoreSimulator/Devices/64E0D907-16AD-41A9-9667-4B3C701D4F1B/data/Containers/Data/Application/488A8AAD-EF4B-452D-9A8A-67307C489C72/Library/example%20file.mp3"
let url = URL(string: urlPath)!
let item = DefaultAudioItem(audioUrl: filePath, sourceType: .file)
let controller = AudioController()
try? controller.player.load(item: item, playWhenReady: true)
I'm sure that the problem is the whitespaces but I don't know with which character substitutes it.
Can someone help me, please?

URL Object is nil after creating it with let constant string url

Why does the first example give me a nil and the second example give me a valid URL object. I am trying to use this jsonUrlString constant and it's not working.
1)
let jsonUrlString = """
https://myURI.domain.com/
"""
let temp = URL(string: jsonUrlString)
2)
let temp = URL(string: "https://myURI.domain.com/")
The first example has lots of extra spaces in the URL so it's not valid.
It's the same as:
let temp = URL(string: " https://myURI.domain.com/")
It would work if you had:
let jsonUrlString = """
https://myURI.domain.com/
"""
This defines the string without the extra spaces.

HttpRequest with multiple parameters swift

I'm trying to create a request with multiple parameters using Swift. So far I managed to create with one parameter but not with multiple.
I tried to use a Dictionary but couldn't do it.
Here is my actual code:
let protocolo = txtProtocolo.text!
var request = URLRequest(url: url)
let parameters = "protocolo=\(protocolo) "
request.httpMethod = "POST"
request.httpBody = parameters.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request)
{ (data, response, error) in
....
I'm trying to do something like this:
let dictionary = ["protocolo":protocolo,
"secondParameter": "value"]
And use this dictionary as httpBody.
Thanks in advance for your help.
If you have the option use Alamofire. It is very good :)
But if you want to use the dictionary. It seems you have to convert it to a string. Did you try something like
let parameters = ["auth":"asdf", "width":"123"]
let parametersString = (parameters.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}) as Array).joined(separator: "&")
And use the parametersString as the parameter

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)
}

Reading URLS in JSON api with swift

For work we have a third party company which supply a JSON api for some functionality. The JSON contains urls which I try to map in my code with URL(string: ...) but this fails on some urls which have spaces.
For example:
var str = "https://google.com/article/test test.html"
let url = URL(string: str) //nil
Should I ask the third party to encode their URLs ?
Is this normal or should I try to add encoding myself?
Encoding myself is hard I think because the path should be encoded different from the query and the host shouldn't be encoded etc.
Or am I overthinking this?
If the URL contains spaces in its path, escape the characters with addingPercentEncoding(withAllowedCharacters passing the urlPathAllowed character set:
let str = "https://google.com/article/test test.html"
if let escapedString = str.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed),
let url = URL(string:escapedString) {
print(url)
} else {
print("url \(str) could not be encoded")
}
What I would do if I were you, is to split the string up on the space, try converting each of the elements to a url, and when that works save it in your variable.
var str = "https://google.com/article/test test.html"
var url: URL? = nil
for urlString in str.components(separatedBy: .whitespacesAndNewlines) {
let url = URL(string: urlString)
if url != nil {
break
}
}
// url might be nil here, so test for value before using it
If each URL that you get from the API is in the format in your example, you can instead just grab the first element after spitting the string.
var str = "https://google.com/article/test test.html"
if let urlString = str.components(separatedBy: .whitespacesAndNewlines).first {
let url = URL(string: urlString)
}
// url might be nil here, so test for value before using it