Fast URL handling
This is my question; I want to get some data from url, this is the code:
let internetURL = NSURL(string:"http://www.example.org")
let siteURL = NSURLRequest(URL: internetURL!)
let siteData = NSURLConnection(request: siteURL, delegate: nil, startImmediately: true)
let strSiteData = NSString(data: siteData, encoding: NSUTF8StringEncoding)
when i write this Xcode gives me the following error:
Additional argument "encoding" when called
on the last line. How can I do?
+3
source to share
2 answers
You can do it like this:
var data = NSMutableData()
func someMethod()
{
let internetURL = NSURL(string:"http://www.google.com")
let siteURL = NSURLRequest(URL: internetURL)
let siteData = NSURLConnection(request: siteURL, delegate: self,
startImmediately: true)
}
func connection(connection: NSURLConnection!, didReceiveData _data: NSData!)
{
self.data.appendData(_data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
var responseStr = NSString(data:self.data, encoding:NSUTF8StringEncoding)
}
+5
source to share
The error message sucks.
If you run it in a playground, you will see that siteData is an NSURLConnection object. Not an NSData object. This is why it won't compile.
The correct way to create a string from a url is:
let internetURL = NSURL(string:"http://www.example.org")
var datastring = NSString(contentsOfURL: internetURL!, usedEncoding: nil, error: nil)
Using it NSURLConnection
correctly gets complicated as it is a low level API that should only be used if you are doing something out of the ordinary. Proper use of this requires that you understand and interact with the TCP / IP stack.
0
source to share