Fortunately, networking on watchOS is incredibly easy. In traditional Apple fashion, “it just works.” We can use the NSURLSession class to make network requests, download files in the background, and upload files. If you want to use a third-party networking library, such as AFNetworking or Alamofire, you can use them just as on iOS, so long as they use NSURLSession and not its predecessor, NSURLConnection.[8] One thing that’s transparent to us as watchOS app developers is the actual device used to perform network requests. If the watch’s paired iPhone is connected, NSURLSession connections will use the iPhone as a proxy. Otherwise, the watch will connect to known Wi-Fi networks and perform the request itself. By leaving the network routing behavior as an implementation detail, the watch can do whatever is best for performance and battery life. As developers, we just need to use the same code as on iOS to connect to servers, and it works. We won’t do a full sample project for this, since most projects will have more in-depth networking, with libraries and frameworks, but here’s a simple URL connection for watchOS:
| guard let url = NSURL(string: "https://www.example.com") else { return } |
| |
| let request = NSURLRequest(URL: url) |
| |
| NSURLSession.sharedSession().dataTaskWithRequest(request) { (data: NSData?, |
| response: NSURLResponse?, error: NSError?) -> Void in |
| guard let data = data, |
| html = String(data: data, |
| encoding: NSUTF8StringEncoding) else { return } |
| |
| print("Received HTML: (html)") |
| }.resume() |
In this example, making a network request is simple. First, we make an NSURL instance from a string, bailing early if this fails. Then, we create an NSURLRequest for this URL. If we needed to do additional work on the request, such as adding HTTP headers, we’d do it here. Next, we create a new data task on the shared NSURLSession, passing in the request and a completion handler. The completion handler, having received data from the server as an NSData instance, turns it into a String and prints it. Finally, we call resume on the data task to start it. Just like that, we’re getting data back from a remote server—on our watch! Now that you’ve seen how to get network connections up and running, let’s look at using WatchConnectivity to communicate with the iPhone.
3.144.254.72