3

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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
massimilianos
  • 25
  • 1
  • 3
  • 4
    There are many thing wrong with your code, first of the object return by [`initWithRequest:delegate:startImmediately:`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/index.html#//apple_ref/occ/instm/NSURLConnection/initWithRequest:delegate:startImmediately:) is not an NSData object but a `NSURLConnection`. You need to implement the [`NSURLConnectionDelegate`](https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/index.html). I suggest you read the Apple documentation. – rckoenes Nov 25 '14 at 09:02

2 Answers2

5

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)
}
qwerty
  • 2,065
  • 2
  • 28
  • 39
0

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.

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
  • 2
    I disagree that NSURLConnection is complicated or unusual (but that may be my personal opinion). It is a method to load resources asynchronously without blocking the main thread. (NSURLSession is a more modern one). – You should at least mention that `NSString(contentsOfURL:...)` should be called on a background queue so that it does not block the main UI thread. – Martin R Nov 25 '14 at 09:36
  • It seems that not receive any data :'( – massimilianos Nov 25 '14 at 09:40