I don't understand why this Swift 2 String() won't init

I have this code in an os x playground (XCode Version 7.2 (7C68)):

let urlString = "https:/

let url = NSURL(string: urlString)!

let listData = NSData(contentsOfURL: url)!

var dataString = String(data: listData, encoding: NSUTF8StringEncoding)

print(dataString)

and what seems to me to be equilivent code in an OS X app I'm building:

static func httpRequest(urlString: String) -> String {

if let url = NSURL(string: urlString) {

if let urlData = NSData(contentsOfURL: url) {

return String(data: urlData, encoding: NSUTF8StringEncoding) ?? "httpRequest: string f

/

} else {

return "httpRequest: nsdata failed"

}

} else {

return "httpRequest: nsurl failed"

}

}

The "if let" constructs I added to find out what was happening. I

could use one of the several wrappers around the HTTP get/et. al.,

but I want to understand myself what's happening before I trust

other code.

In the playground the extraction from NSData works and the large

(56K?) string is printed. In the OS X app the String() fails and I

don't understand why.

Why does the String() creation in the OS X app fail?

TIA

(I'm using the "static func" construct inside a "struct" because

this is the only way I have found to create tests without error.)

(I've cross posted this to three groups total to get an answer.)

Mike

For a start, you should not use 'contentsOfURL:', but 'contentsOfURL:options:', which throws an error you can catch and examine.


Next, you should print (or examine in the debugger) the various variables (the original urlString, the url and urlData — at least its length and first few bytes).


Note that if the string you're converting to a URL isn't properly absolute, I guess you might get different results in different execution environments. You need to know what url resolves to, not just what it is.

Thanks Quincey. I'm new to Swift (but not programming). I'm translating a pet project from 2000 into Swift. I'll implement your suggestions and be back (in a few minutes?).

The one obvious gotcha here is App Transport Security.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

DTS will close for the winter holidays at the end of business on Wed, 23 Dec 2015 and re-open on Mon, 4 Jan 2016.

I don't understand why this Swift 2 String() won't init
 
 
Q