User 965
User 965

Reputation: 189

How to read text on a web page in swift for ios

I have a web page that only shows simple text information but I am unsure how to get the text using swift. I am open to using any method as I think this is an easy problem, I am just unsure what to search for to find an answer.

Here is the webpage in question where the last part, "player=bob" can be modified depending on the user. Thanks

http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=bob

Upvotes: 0

Views: 1195

Answers (2)

wd_iOSEngineer
wd_iOSEngineer

Reputation: 11

Do you want to get string from UIWebView or WKWebView?

If you use UIWebView,the first thing you must set UIWebView delegate.

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *newString = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"];
}

The 'newString' is the HTML String in webView.If you want to use real show on page,you need to translate strings. I hope that can help you. If you use WKWebView,this may not work.

Upvotes: 0

Leo Dabus
Leo Dabus

Reputation: 236360

You can use URLSession dataTask(with url:) to download your string data asynchronously:

import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true


let scheme = "http"
let host = "services.runescape.com"
let path = "/m=hiscore_oldschool/index_lite.ws"
let player = "bob"
let queryItem = URLQueryItem(name: "player", value: player)

var urlComponents = URLComponents()
urlComponents.scheme = scheme
urlComponents.host = host
urlComponents.path = path
urlComponents.queryItems = [queryItem]
if let url = urlComponents.url {
    print(url) // "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=bob\n"

    URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error ==  nil, let string = String(data:data, encoding: .utf8) else { return }
        print(string)  // 58009,1806,205602075\n348,99,59484076\n14451,99,16670682\n22760,99,16641294\n4372,99,35456433\n64147,99,13034611\n14021,99,13034458\n269415,79,1897071\n57799,99,13034505\n42650,87,4136181\n262455,70,742935\n12795,99,13034536\n254495,60,275820\n89361,75,1213576\n190818,62,341931\n272854,60,284103\n111969,66,507089\n66399,74,1177748\n64643,72,915704\n10231,99,13059448\n187538,52,132708\n162920,50,106555\n175923,62,351621\n295606,46,68990\n327642,1\n179487,5\n72965,106\n-1,-1\n-1,-1\n48877,85\n-1,-1\n24712,15\n-1,-1\n\n"
    }.resume()
}

Upvotes: 1

Related Questions