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];
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With