Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String With Contents Of URL?

Tags:

ios

swift

So before I downloaded the recent update, the following code worked for me:

var g_home_url = String.stringWithContentsOfURL(NSURL(string: url_string), encoding: NSUTF8StringEncoding, error: nil) // Gives me an error: "String.Type does not have a member names stringWithContentsOfUrl"

I am confused. What is the proper way to acieve the following objective-c method in swift?

NSString * g_home_url = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:home_url] encoding:NSUTF8StringEncoding error:nil];
like image 526
imnilly Avatar asked Oct 23 '14 15:10

imnilly


2 Answers

Use the -initWithContentsOfURL:encoding:error: instance method instead of the +stringWithContentsOfURL:encoding:error: class convenience initializer.

var g_home_url = String(contentsOfURL: NSURL(string: url_string)!, encoding: NSUTF8StringEncoding, error: nil)

I have no idea if class convenience initializers are now unsupported in Swift, but it would make sense as they were just shorthands for the alloc-init boilerplate, which doesn't exist in Swift.

like image 159
Guillaume Algis Avatar answered Sep 23 '22 06:09

Guillaume Algis


For Swift 3 you'll have to use String(contentsOf:encoding:). It throws.

do {
    var content = try String(contentsOf:URL(string: "http://your-URI-here")!)
}
catch let error {
    // Error handling
}
like image 24
Niklas Berglund Avatar answered Sep 20 '22 06:09

Niklas Berglund