Reputation: 315
I have tried all the methods I came across on Google but none work. So my question is how would I get the contents of a web page using Swift? Like send an HTTP Request to a website and get the source of the page.
Any help or references welcome :D.
I have tried Alamofire and a bunch of other projects on Github as well.
Upvotes: 0
Views: 237
Reputation: 7615
How about NSURLConnection
and NSURLRequest
?
sendAsynchronousRequest:...
passes an NSData
object into the completion handler alongside the NSURLRequest. sendSynchronousRequest:...
(please avoid) returns an NSData
object. Starting a request with start requires you to have hooked up a delegate to that request that implements NSURLConnectionDelegate
where various methods are called as data comes in or the request fails. I'd recommend sendAsynchronousRequest:...
.
Upvotes: 0
Reputation: 13862
This code will get you the source code of a website in text form:
let source = NSString(contentsOfURL: NSURL(string: "http://www.google.com"), encoding: NSASCIIStringEncoding, error: nil)
Edit: If the website contains non-ascii characters, you can of course use 'NSUTF8StringEncoding'. If you don't want to block the main thread you should of course use an async_dispatch call.
Upvotes: 4