How to get text from Web page in macOS via Swift?
for iOS, in the webview's delegate method
func webViewDidFinishLoad(_ webView: UIWebView) {
var string = webView.stringByEvaluatingJavaScript(from: "document.body.textContent")
print(string)
}
for macOS, in the webview's navigation delegate:
override func viewDidLoad() {
webview.nagivationDelegate = self
...
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.body.textContent") { (string, error) in
print(string)
}
}
How to read text on a web page in swift for ios
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()
}
How to make HTTP request in Swift?
You can use URL
, URLRequest
and URLSession
or NSURLConnection
as you'd normally do in Objective-C. Note that for iOS 7.0 and later, URLSession
is preferred.
Using URLSession
Initialize a URL
object and a URLSessionDataTask
from URLSession
. Then run the task with resume()
.
let url = URL(string: "http://www.stackoverflow.com")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
task.resume()
Using NSURLConnection
First, initialize a URL
and a URLRequest
:
let url = URL(string: "http://www.stackoverflow.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
Then, you can load the request asynchronously with:
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {(response, data, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
Or you can initialize an NSURLConnection
:
let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true)
Just make sure to set your delegate to something other than nil
and use the delegate methods to work with the response and data received.
For more detail, check the documentation for the NSURLConnectionDataDelegate
protocol
Testing on an Xcode playground
If you want to try this code on a Xcode playground, add import PlaygroundSupport
to your playground, as well as the following call:
PlaygroundPage.current.needsIndefiniteExecution = true
This will allow you to use asynchronous code in playgrounds.
How do I retrieve text and images from websites (in HTML or JSON) on iOS Swift?
Question 1: Not all websites expose their content formatted as JSON.
Question 2: I think you should look at a couple of resources. First Ray Wenderlich has a tutorial on how to parse HTML. Although it is using Objective-C you should be able to learn quite a lot there.
When you have read that tutorial I would recommend you look at the Swift library Alamofire. There is another tutorial on the Wenderlich site covering this library.
Happy coding!
Related Topics
How to Stop an Infinitely Rotating Image? and How Does One Implement Removeallanimations
How to Set Cadisplaylink in Swift with Weak Reference Between Target and Cadisplaylink Instance
Swift 2: Multiline Mkpointannotation
Value of Type 'Authdataresult' Has No Member 'Uid'
How to Deallocate All References Elements from an Array
What Does the Snapshot/Observer Code Do in Firebase
How to Use Core Data Value from Picker? #Swiftui #Coredata
Swift: How to Handle Video and Photo Results from a PHPicker
What Does Cloning a Github Repository Mean
Passing Unknown Number of Arguments in a Function
Create a Weak Container in Swift That Accepts a Native Swift Protocol
Ios13 Uialertcontroller with Custom View & Preferredstyle as Actionsheet Grayscale All Colors
Use Huge Numbers in Apple Swift
How to Define an Array of a Particular Enum Case in Swift
Why Function Return Nil Firebase Swift