String(contentsOfURL:) in Swift 3
According to the Swift 3 Migration Guide,
Users may need to manually migrate calls to String(contentsOfURL:usedEncoding:) to String(contentsOf:usedEncoding:)
String With Contents Of URL?
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.
Using Data with ContentsOfUrl
I recommend to use something like this in Swift 3, to load JSON data dataTask
is more appropriate than downloadTask
.
let endpointURL = URL(string: "http://foobar.com")
let dataTask = URLSession.shared.dataTask(with: endpointURL!) { data, response, error in
guard error == nil else {
print(error!)
return
}
do {
// the assumed result type is `[[String:Any]]` cast it to the expected type
if let jsonArray = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
print(jsonArray)
}
} catch {
print(error)
}
}
dataTask.resume()
In Swift 3, how to fix an error about argument labels do not match any available overloads for String type?
This method has been updated to (in the context of your example):
dataString = try String(contentsOf: fileDestinationUrl)
In Swift 3, all function params now have labels unless specifically defined otherwise. This in practice often means the last part of a method name moves to the first params label.
NSData init?(contentsOf url: URL) migration from Swift 2 to Swift 3
The migration consists of some changes in those methods' signatures, namely, the types they accept.
In Swift 2, NSData(contentsOfURL:)
and UIImage(data:)
take NSURL
and NSData
, respectively.
Currently, they have been changed to NSData(contentsOf:)
and UIImage(data:)
that accept, respectively, URL
(struct
) and Data
(instead of NSData
); as a result, the casts are necessary unless you constructed your URL from type URL
instead of NSURL
.
You could use, instead, Data(contentsOf: URL)
to avoid the cast as well.
Is this string object creation in swift?
Does it create a String object?
Yes, it creates a string from the contents of the URL given by contentsOfURL
and using the character encoding given by encoding
. It's analogous to the following Objective-C code:
NSString *content = [NSString stringWithContentsOfURL:contentsOfURL
encoding:encoding
error:&error];
The if let
part is a form of conditional statement. let
is used to assign a value to an immutable variable. Using it in a conditional as in your example only allows the body of the conditional statement to execute if that assignment succeeds. So, if some error occurs while the data at the given URL is being fetched or if the string cannot be created for some reason, the condition fails and the body isn't executed. The whole snippet might be written like this in Objective-C:
NSString *content = [NSString stringWithContentsOfURL:contentsOfURL
encoding:encoding
error:&error];
if (content != nil) {
// do something with content
}
Converting URL to String and back again
fileURLWithPath()
is used to convert a plain file path (e.g. "/path/to/file") to an URL. Your urlString
is a full URL string including the scheme, so you should use
let url = NSURL(string: urlstring)
to convert it back to NSURL
. Example:
let urlstring = "file:///Users/Me/Desktop/Doc.txt"
let url = NSURL(string: urlstring)
println("the url = \(url!)")
// the url = file:///Users/Me/Desktop/Doc.txt
NSXMLParser contentsOfURL Vs Data
There is no semantic difference between the two variants.
For http(s) urls you should prefer init(data:)
or XMLParser(data:)
, but you should not load you data with NSData(contentsOf:)
. The reason is that the contentsOf:
variants will block the current thread with a synchronous request. You should instead load the data asynchronously with NSURLSession
.
You should use XMLParser(contentsOf:)
and Data(contentsOf:)
only for file urls.
Related Topics
How to Create a Window with Transparent Background with Swift on Osx
How to Import a Swift Function Declared in a Compiled .Swiftmodule into Another Swift File
What's the Equivalent to String.Localizedstringwithformat(_:_:) for Swiftui's Localizedstringkey
How Does Dictionary Use the Equatable Protocol in Swift
Check If Variable Is an Optional, and What Type It Wraps
Implementing Nscopying in Swift with Subclasses
How to Clear Alamofireimage Setimagewithurl Cache
Swiftui Set Position to Center of Different View
Make Int Round Off to Nearest Value
How to Track More Than 4 Images at a Time with Arkit
Division Not Working Properly in Swift
Global Function Sequence(State:Next:) and Type Inference
Swift: How to Assign a Variable by Reference, Not by Value
Error: Use of Unresolved Identifier 'Process'
Swiftyjson - Call Can Throw, But It Is Marked with 'Try' and the Error Is Not Handled