Translation: Damonwong; Proofreading: Numbbbbb, BigNerdCoding; Finalized: Forelax

Translator’s Note: We have translated this article before. The author of the original article updated this article this year, and we have translated the updated article and republished it.

For most applications, access to file resources is required. These file resources may be in your application installation package, in the file system, or on a web server. You need to have some way of embodying them in your code. With The Apple platform, you have two main options, string or URL.

If you’ve ever used a browser’s address bar or entered an address in a terminal, you might choose to use strings. After all, you can only type strings in those places. Although many older apis in Cocoa and Cocoa Touch SDKs take both urls and strings (often referred to as “path” for these apis) as arguments, more and more apis tend to use ONLY URL objects. URL objects have more advantages than string paths, the most obvious advantage being that you can access different parts of the URL directly through properties, rather than having to write a parsing component to parse different parts of the string.

Following in my footsteps, let’s learn how to create and use URL objects in Swift applications.

Create one in SwiftURLobject

There are several constructors and factory methods available for creating URL objects in Swift, but I’ll cover some of the more useful initialization methods.

init? (string URLString: String)

This is the common and most commonly used initialization method. Convert a Swift string used to represent a URL into a URL object. But not all strings are valid to represent a URL, so this is a failable constructor. Since some characters cannot be used in the URL, URL encoding is required to convert these unusable characters into codes that can be sent in the URL. The one I’ve personally seen the most is %20, which is the “space” character. This constructor requires valid characters, and it doesn’t do urL-encoding conversions for you. If the string contains characters or content that cannot be converted to a valid URL, the constructor returns nil.

let NSHipster = URL(string: "http://nshipster.com/") Return a valid URL
let invalidURL = URL(string: "www.example.com/This is a sentence") / / returns nil
Copy the code

This constructor is actually a convenience constructor for the following constructor.

init? (string: String, relativeTo: URL?)

This is a specified constructor. Like the constructor above, it is a failable constructor and requires a URL-like Swift string and an optional baseURL object, which is itself a URL object. If baseURL is nil, then internally, like the first constructor, a URL object is generated from the supplied URL string.

let NSHipsterTwo = URL(string: "http://nshipster.com/", relativeTo: nil) // Return a valid NSHipster URL
let article = URL(string: "ios9/", relativeTo: NSHipster) / / returns the URL "http://nshipster.com/ios9/"
Copy the code

init(fileURLWithPath: String, isDirectory: Bool)

This constructor is similar to the previous one, but its string argument points to a local file or directory. I’m not quite sure why there is a special version of a local file, I guess it’s probably optimized (at least it needs to start with a scheme file, not HTTP or something). Although there is a constructor that does not require passing isDirectory arguments, Apple recommends using this method if you know whether it is a directory. In my opinion, it is possible that another constructor internally determines whether the input parameter is a directory, and this method avoids checking by passing in the parameter.

init(fileURLWithPath: String, isDirectory: Bool, relativeTo: URL?)

This method is new in iOS 9 and is similar to the previous one, but with a relativeToURL parameter added. Like the previous constructor, it returns a URL object that appends the path to the baseURL. Use this initialization method when you need to repeatedly access different files in a directory for something. You can use the directory where the file resides as baseURL, and then just need a filename as the Swift string path to create the URL object.

Roll the URL back to the Swift string

Sometimes you need to turn the URL object back to the Swift string, especially when working with older apis or showing users. Thankfully, urls provide a simple read-only property to solve this problem: the absoluteString. Just call this property on your URL object:

letarticleString = article? .absoluteString/ / articleString now include the value = "http://nshipster.com/ios9/"
Copy the code

In this example, we use the relativeToURL version of the constructor to define an article constant, which is resolved as the full URL (in this case, a path) from Scheme. If the URL has a file extension, query, or fragment, it can still be parsed. The original article object is returned by a failable constructor, which is why there is a Swift optional access there.

Modify a URL object

Each of the following methods returns a new URL object based on the invoked URL object when the requested modification is complete. They do not change the URL object from which they are called.

func appendingPathComponent(String, isDirectory: Bool) -> URL

This method can be used to add more path components to your URL, such as when you want to add a file to your directory (stored in the URL returned by this method call). Like the initialization method we mentioned earlier, this method has a version with no isDirectory argument, but whether you know it is a directory or not, it is recommended that you use this method to ensure that the metadata is stored in the correct directory.

func deletingLastPathComponent() -> URL

This method will return the new URL object with the last path component removed. This method applies to the path part of the URL, leaving other parts of the URL unaffected, such as the domain name. So we can do it like this:

let articleTwo = NSHipster? .appendingPathComponent("ios9", isDirectory: true)
/ / articleTwo now contains the URL of the character is "http://nshipster.com/ios9/"

letdeletePathComp = articleTwo? .deletingLastPathComponent//deletePathComp now contains the URL character "http://nshipster.com/"
Copy the code

: before Swift 4.2 deletingLastPathComponent is an attribute, so don’t need to add parentheses when calling. In version 4.2, deletingLastPathComponent becomes a method So if you run on 4.2 above a piece of code, in articleTwo needed? . DeletingLastPathComponent finally add a bracket can run correctly

If there is no path information, it might be a little strange. For fun, I chain call several times URLByDeletingLastPathComponent, finally just added “.. / “, similar to the command line (CD..) In the previous directory.

There are of course several other modification methods and properties, but these are probably the most common.

conclusion

If you’re interested in the URL format specification, check out the RFC documentation in Apple’s URL Reference on how to handle urls. The string used for initialization must conform to RFC 2396, and the URL will be parsed according to RFC 1738 and RFC 1808. These specifications are a lot, but you can find all the possible information about urls, URIs, and so on.

If you look through the documentation of the URL, you can also see that it has baseURL, host, Query, fragment, and many other attributes, all of which are available in the Apple documentation. For me, though, absoluteString is the one I use most on a daily basis, with occasional pathExtension

I hope you found this article helpful. Don’t hesitate to share this article on Twitter or other social media if you find it useful. Of course, if you have any questions, please feel free to contact me on the contact page or Twitter@CodingExplorer. I’ll help you as much as I can. thank you

reference

URL Class Reference – Apple Inc.

This article is translated by SwiftGG translation team and has been authorized to be translated by the authors. Please visit swift.gg for the latest articles.