Swift URL Handling

6.5k views Asked by At

This is my question; I want to get some data from an 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 give me the following error:

Extra argument 'encoding' in call

on the last line. How can I do?

2

There are 2 answers

2
Abhi Beckert On

The error message sucks.

If you run it in playground, you can see that siteData is an NSURLConnection object. Not an NSData object. That's 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 NSURLConnection properly is complicated as it's a low level API that should only be used if you're doing something unusual. Using it properly requires you to understand and interact with the TCP/IP stack.

6
qwerty On

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