Web PDF - Applied College – Qassim University

Document Details

FertileAcademicArt8149

Uploaded by FertileAcademicArt8149

Applied College – Qassim University

Tags

web development urls web data programming

Summary

This document is a presentation about working with the web. It covers the basics of URLs, and how web data is sent and received. It also briefly touches on APIs.

Full Transcript

Applied College – Qassim University Kingdom of Saudi Arabia ‫اﻟﻣﻣﻠﻛﺔ اﻟﻌرﺑﯾﺔ اﻟﺳﻌودﯾﺔ‬ Ministry of education ‫وزارة اﻟﺗﻌﻠﯾم‬ Qassim University...

Applied College – Qassim University Kingdom of Saudi Arabia ‫اﻟﻣﻣﻠﻛﺔ اﻟﻌرﺑﯾﺔ اﻟﺳﻌودﯾﺔ‬ Ministry of education ‫وزارة اﻟﺗﻌﻠﯾم‬ Qassim University ‫ﺟﺎﻣﻌﺔ اﻟﻘﺻﯾم‬ Applied College ‫اﻟﻛﻠﯾﺔ اﻟﺗطﺑﯾﻘﯾﺔ‬ Chapter : Working with the Web ITCW 209 1 All rights reserved for Applied College - Qassim University Outline Applied College – Qassim University 2 All rights reserved for Applied College - Qassim University Applied College – Qassim University 1. Introduction 3 All rights reserved for Applied College - Qassim University 1. Introduction Applied College – Qassim University In this lesson, you'll learn the basics of how web data is sent and received, how URLs work, and how to fetch data for use in your app. Along the way, you'll build a playground that uses a URLSession to fetch and display a photo. In future lessons, you'll learn how to turn data you fetch from the web into custom model data, where to put code that performs network requests, and best practices for displaying web data in your app. 4 All rights reserved for Applied College - Qassim University Applied College – Qassim University 2. The Basics 5 All rights reserved for Applied College - Qassim University 2. The Basics Applied College – Qassim University When you open a website, you send a network request that travels over the internet until it arrives at a web server—a specialized computer that's programmed to listen for your requests and to respond to them. The web address you use determines which server receives the request and what response you'll get. You probably already know that a web address is also called a URL, which stands for uniform resource locator. But have you ever wondered what all the pieces of those sometimes long URLs are? 6 All rights reserved for Applied College - Qassim University 2. JSON Basics Applied College – Qassim University A URL consists of two required parts: 7 All rights reserved for Applied College - Qassim University 2. JSON Basics Applied College – Qassim University URLs can get more specific and more complex by including subdomains, ports, paths, or query parameters. 8 All rights reserved for Applied College - Qassim University 2. JSON Basics Applied College – Qassim University Protocol Similar to protocols in iOS, a web protocol specifies how the browser and the server communicate with each other. In general, websites use the HTTP or HTTPS protocol. Subdomain A subdomain can be used to point to a more specific server or to redirect to another URL. 9 All rights reserved for Applied College - Qassim University 2. JSON Basics Applied College – Qassim University Domain Name A domain name is a unique reference to a specific website and always includes a host name (like “apple” or “itunes”) and a top-level domain (like “.com” or “.org”). A domain name points to specific servers that handle all the requests that go to that domain. Port Ports are a standard feature of the Internet Protocol (IP), on which HTTP and HTTPS are built. Every computer connecting to the internet via IP can expose multiple ports, each with its own number. 10 All rights reserved for Applied College - Qassim University 2. JSON Basics Applied College – Qassim University Path The path refers to a specific file or subdirectory on a server. For example, if you navigate to https://apple.com/iphone/ the server will respond with the HTML that displays information about iPhone products. Query Parameters A query provides the server with even more specifics about a request. Queries work like dictionaries in Swift, with keys and values that give the server parameters for generating a page with the desired information. For example, if you navigate to https://www.apple.com/us/search/iPhone?sel=explore&page=2, you're telling the Search page to display the second page of results for the keyword “iPhone” under the Explore tab. 11 All rights reserved for Applied College - Qassim University 2. JSON Basics Applied College – Qassim University Request Type The request type is also known as the HTTP method, and the two most common are GET and POST. As you'd expect, GET is used to request information from a server, and POST is used to send a body of information to a server. When you load a website, you're sending a GET request. When you submit a form on a website, you're sending a POST request. Headers Like the path and query parameters, the headers of a network request work in the same way as a dictionary: with keys and values that tell the server how to handle the request. (The URL doesn't include the headers, because the user doesn't usually need to see them.) One common header parameter, called User-Agent, is a string that identifies the system performing the request. 12 All rights reserved for Applied College - Qassim University 2. JSON Basics Applied College – Qassim University Body The body of a request includes the data that was sent or received. When you receive a response to a GET request, it will also have a body. For example, when you request the information for a website, the resources that make up the site—its HTML, CSS, and images—are all included as bodies of the network request. When your app sends a POST request, it will send a body of information— whether plain text, JSON, or a file—to be posted to the server. 13 All rights reserved for Applied College - Qassim University Applied College – Qassim University 3. Create a URL 14 All rights reserved for Applied College - Qassim University 3. Create a URL Applied College – Qassim University Creating a URL object is simple: Use the init?(string: String) initializer of URL type, which returns an optional URL. import Foundation let url = URL(string: "https://www.apple.com")! Why does that code use the ! operator? You've already learned that the failable initializer will return an optional URL instance. If you look at the documentation for the initializer, you'll find a discussion that explains when the initializer will fail: Returns nil if a URL cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string). 15 All rights reserved for Applied College - Qassim University 3. Create a URL Applied College – Qassim University In fact, URLs can contain any of the following characters: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456 789_~:/?#[]@!$&'()*+,;=`. 16 All rights reserved for Applied College - Qassim University 3. Create a URL Applied College – Qassim University Activity: You can experiment with printing out its different properties. For example, use the scheme property on url to print the HTTPS protocol, use host to print the domain, or use query to print the list of query parameters. (Note that if you try to print a property with an optional type, such as query, directly, the playground will warn you that it has implicitly coerced the expression. You can get around these errors with judicious use of force-unwrapping.) 17 All rights reserved for Applied College - Qassim University 3. Create a URL Applied College – Qassim University Activity: You can experiment with printing out its different properties. For example, use the scheme property on url to print the HTTPS protocol, use host to print the domain, or use query to print the list of query parameters. (Note that if you try to print a property with an optional type, such as query, directly, the playground will warn you that it has implicitly coerced the expression. You can get around these errors with judicious use of force-unwrapping.) 18 All rights reserved for Applied College - Qassim University Applied College – Qassim University 4. Create and Execute A Network Request 19 All rights reserved for Applied College - Qassim University 4. Create and Execute a Network Request Applied College – Qassim University URLSession class is used to create and execute a network request. Any app can access a shared URLSession instance by accessing the shared type property. This session is in charge of managing all the network requests you send, and it allows you to run code when each request is finished. 20 All rights reserved for Applied College - Qassim University 4. Create and Execute a Network Request Applied College – Qassim University Request a Data Task Start by creating a URLSessionDataTask object from the shared URLSession using the dataTask(with: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) method. CompletionHandler: “allows you to provide code that will run when the request is finished, and it provides access to instances of Data?, URLResponse?, and Error? 21 All rights reserved for Applied College - Qassim University 4. Create and Execute a Network Request Applied College – Qassim University Request a Data Task Data?: the body of the response. URLResponse?: information about the response itself, including a status code and any header fields included in the response. Error? represents any error that may have occurred while running the network request. 22 All rights reserved for Applied College - Qassim University 4. Create and Execute a Network Request Applied College – Qassim University Request a Data Task @escaping : A function that accepts a closure argument can use the argument in two ways: It might execute the closure as part of its code—the map(_:). Or the closure might be used much later. This is the case when you create a data task. Most URL session-related instance methods that access the network return control to the calling code immediately and handle network access while your code continues to run. 23 All rights reserved for Applied College - Qassim University 4. Create and Execute a Network Request Applied College – Qassim University Request a Data Task @escaping : A function that accepts a closure argument can use the argument in two ways: It might execute the closure as part of its code—the map(_:). Or the closure might be used much later. This is the case when you create a data task. Most URL session-related instance methods that access the network return control to the calling code immediately and handle network access while your code continues to run. 24 All rights reserved for Applied College - Qassim University 4. Create and Execute a Network Request Applied College – Qassim University Request a Data Task Go ahead and create your first URLSessionDataTask. As you begin typing the following code, use the autocompletion feature to fill in the parameters. Remember, once you've navigated to the completionHandler parameter, you can press Return to expand the closure—at which point you can give names to its parameters (Data?, URLResponse?, and Error?). Finish the completion handler closure with a print statement. 25 All rights reserved for Applied College - Qassim University 4. Create and Execute a Network Request Applied College – Qassim University Request a Data Task let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if let data = data { print(data) } } Send the Request At this point, you've created a request, but you haven't sent it. To send the request, you'll use the resume() method on the data task instance. Go ahead and resume the task in your playground. task.resume() 26 All rights reserved for Applied College - Qassim University 4. Create and Execute a Network Request Applied College – Qassim University Process the response To get an idea of what Data looks like, update your code to use the older NSData. let url = URL(string: "https://www.apple.com")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if let data = data { print(data as NSData) } } task.resume() Console Output: {length = 189449, bytes = 0x0a0a0a09 0a0a0a09 0a0a090a 0a0a090a... 0a0a0a0a 090a0a0a } 27 All rights reserved for Applied College - Qassim University 4. Create and Execute a Network Request Applied College – Qassim University Process the response You'll notice the result has a truncated bytes property with incomprehensible values. but—since you're a human—you'll want to serialize the data into a more legible string. You can use the String(init: Data, encoding: String.Encoding) initializer to return a String from Data, as long as the initializer can parse the data correctly. 28 All rights reserved for Applied College - Qassim University 4. Create and Execute a Network Request Applied College – Qassim University Process the response let url = URL(string: "https://www.apple.com")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if let data = data , let string = String(data:data,encoding:.utf8){ print(string) } } task.resume() 29 All rights reserved for Applied College - Qassim University 4. Create and Execute a Network Request Applied College – Qassim University Process the response More often than not, you'll want to use a network request to fetch raw information (instead of the website's HTML), which you can serialize into model objects and display in your app. One of the most common formats on the web is called JavaScript Object Notation, or JSON. You'll do some work with JSON in the next lesson. For now, you'll learn how to request information from a web service, or API, that returns JSON. To wrap up this lesson, you'll print the JSON to the console, just like you did with the HTML in the earlier example. 30 All rights reserved for Applied College - Qassim University Applied College – Qassim University 5. Work with an API 31 All rights reserved for Applied College - Qassim University 5. Work with an API Applied College – Qassim University API stands for application programming interface. An API is a set of routines, protocols, or tools for building software applications. Each framework or class you've used could be considered an API like UIKit. In the context of working with the web, an API usually refers to a website or service that enables information to be sent or received via network requests. 32 All rights reserved for Applied College - Qassim University 5. Work with an API Applied College – Qassim University Many websites and organizations offer APIs that allow developers to work with different types of information. For example, the NASA Astronomy Picture of the Day (APOD) API serves up a beautiful image from our universe daily, along with a brief description of the image—powering the popular Astronomy Picture of the Day website. By requesting data from the APOD API, you can build an app that displays the same photo and the same description. 33 All rights reserved for Applied College - Qassim University 5. Work with an API Applied College – Qassim University A URL consists of:Domain name: (e.g., api.nasa.gov) Path: (e.g., /planetary/apod) Query Parameters: (e.g., ?api_key=DEMO_KEY) APIs work by reading the path and query parameters you send to the server.APIs usually provide documentation on how to structure URLs and interpret responses. 34 All rights reserved for Applied College - Qassim University 5. Work with an API Applied College – Qassim University NASA APOD API Documentation Visit https://api.nasa.gov for NASA API documentation. API documentation includes: Service description Sample image and HTTP request List of optional query parameters Example query with api_key. 35 All rights reserved for Applied College - Qassim University 5. Work with an API Applied College – Qassim University NASA APOD API Documentation API Key and Rate Limits API Key: A tool to monitor who uses the API and how often. Many APIs provide a demo key for limited requests. Rate limits for the NASA API: Demo Key: 30 requests per hour, 50 per day. Registered Key: 1,000 requests per hour. 36 All rights reserved for Applied College - Qassim University 5. Work with an API Applied College – Qassim University Creating Your First API Request: Use this URL for the NASA APOD API: let url = URL(string: "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")! You may need to register for your own API key if you exceed the demo key limits. 37 All rights reserved for Applied College - Qassim University 5. Work with an API Applied College – Qassim University Swift Code: Making the API Request PlaygroundPage.current.needsIndefiniteExecution = true let url = URL(string: "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if let data = data, let string = String(data: data, encoding:.utf8) { print(string) } PlaygroundPage.current.finishExecution() } task.resume() 38 All rights reserved for Applied College - Qassim University 5. Work with an API Applied College – Qassim University Sample API Response API responses are typically returned in JSON format: { "copyright":"Maxime Daviron", "date":"2020-01-13", "explanation":"Tonight the Moon is young again...", "hdurl":"https://apod.nasa.gov/apod/image/1811/SHonda-moon-VLA.jpg", "media_type":"image", "title":"The Old Moon in the Young Moon's Arms", "url":"https://apod.nasa.gov/apod/image/1811/SHonda-moon-VLA1024.jpg" } 39 All rights reserved for Applied College - Qassim University 5. Work with an API Applied College – Qassim University Fetching Specific Date Images Modify the URL to get images from a specific date: https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=YYYY-MM-DD The date format should be YYYY-MM-DD.The API allows fetching images starting from June 16, 1995. 40 All rights reserved for Applied College - Qassim University Applied College – Qassim University 6. Modify URL with URL Components 41 All rights reserved for Applied College - Qassim University 6. Modify URL with URL Components Applied College – Qassim University Handling Invalid Characters in URLs URLs have restrictions on what characters can be included. For example, the space character is not allowed in URLs. Solution: Use percent-encoding to represent invalid characters. Example: Space is represented as %20. 42 All rights reserved for Applied College - Qassim University 6. Modify URL with URL Components Applied College – Qassim University Dynamically Generating URLs Often, URLs need to be created dynamically, especially with query parameters. Instead of manually encoding invalid characters, use URLComponents to safely build URLs. 43 All rights reserved for Applied College - Qassim University 6. Modify URL with URL Components Applied College – Qassim University Introducing URLComponents URLComponents: A type in the Foundation framework that helps safely create and manipulate URLs. It can parse, read, and construct URLs with query parameters. Ideal for generating dynamic URLs in a structured and error- free way. 44 All rights reserved for Applied College - Qassim University 6. Modify URL with URL Components Applied College – Qassim University Working with URLQueryItems URLQueryItem: Represents a single key/value pair in a query string (e.g., ?key=value). Similar to a dictionary [String: String], but designed specifically for URLs. A URLQueryItem is simply a single key/value pair, much like a [String:String] dictionary with one element. Use the map() function to map a [String: String] to an array of URLQueryItems to pass to the queryItems property on URLComponents. 45 All rights reserved for Applied College - Qassim University 6. Modify URL with URL Components Applied College – Qassim University Example: Creating a URL with Query Parameters Create a new URLComponents instance that uses the base URL of the NASA APOD API (https://api.nasa.gov/planetary/apod). Then add URLQueryItems for the api_key and a date. var urlComponents = URLComponents(string: "https://api.nasa.gov/planetary/apod")! urlComponents.queryItems = [ "api_key": "DEMO_KEY", "date": "2013-07-16" ].map { URLQueryItem(name: $0.key, value: $0.value) } - In this example:Base URL: https://api.nasa.gov/planetary/apod - Query Parameters: api_key and date. 46 All rights reserved for Applied College - Qassim University 6. Modify URL with URL Components Applied College – Qassim University Using URLComponents with URLSession let task = URLSession.shared.dataTask(with: urlComponents.url!) { (data, response, error) in if let data = data, let string = String(data: data, encoding:.utf8) { print(string) } } task.resume() The dataTask sends a request using the generated URL with query parameters.The response will be similar to previous results. 47 All rights reserved for Applied College - Qassim University 6. Modify URL with URL Components Applied College – Qassim University Using URLComponents with URLSession let task = URLSession.shared.dataTask(with: urlComponents.url!) { (data, response, error) in if let data = data, let string = String(data: data, encoding:.utf8) { print(string) } PlaygroundPage.current.finishExecution() } task.resume() The dataTask sends a request using the generated URL with query parameters.The response will be similar to previous results. 48 All rights reserved for Applied College - Qassim University

Use Quizgecko on...
Browser
Browser