Hola, Apple

1

Hablemos de iOS

2

Conozcamos XCode

3

驴Necesito un iPhone para ser iOS Developer?

Tu primera app en iOS

4

隆Hola, Mundo Apple!

5

Navegaci贸n con UINavigationController

6

Modales en la navegaci贸n

7

Utilizando controles en c贸digo

8

Autolayout vs SwiftUI

9

Autolayout

10

Listas con UITableView

11

Celdas personalizadas para nuestras listas.

12

Persistencia: UserDefaults

Manejo de dependencias

13

CocoaPods

14

Carthage

Servicios Web

15

Primeros pasos para consumir servicios

16

Afinando detalles para consumir servicios

17

Convirtiendo los JSON a modelos

18

Alamofire

Proyecto: PlatziTweets

19

Bienvenido a PlatziTweets

20

Configurando Proyecto

21

Dise帽ando vistas iniciales

22

Configuraci贸n de vistas iniciales

23

Configuraci贸n de registro

24

Descripci贸n de la API de PlatziTweets

25

Conexi贸n de la API y Autenticaci贸n

26

Registro de usuarios

27

Dise帽o del Tweet

28

Obteniendo Tweets

29

Creaci贸n de vista para publicar Tweets

30

Publicando Tweets

31

Borrando Tweets

32

Integraci贸n de la c谩mara

33

Conexi贸n con Firebase

34

Configuraci贸n de XCode para correr app

35

Subir imagen a Firebase

36

Publicar Tweet con imagen

37

Tomando Videos para el Tweet

38

Publicar Tweet con video

39

Detalles del video

40

Accediendo al GPS

41

Implementando mapas con MapsKit

42

Mostrando todos los estudiantes en el mapa

43

Retos del proyecto

En producci贸n

44

Enviar a pruebas con Firebase Distribution

45

Enviar tu aplicaci贸n a APP Store Connect

46

Distribuci贸n de tu app con TestFlight

iOS Avanzado

47

Dark Mode

48

SwiftUI

49

Terminando detalles de una vista con SwiftUI

50

Objective-C

Hola, iOS Developer

51

Felicidades

52

Expert Session: 隆nuevo espacio para resolver tus dudas sobre el desarrollo de Apps para iOS!

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
2 Hrs
28 Min
18 Seg

Primeros pasos para consumir servicios

15/52
Resources

Why is it crucial to learn how to consume web services in mobile development?

The consumption of web services is a fundamental pillar in mobile development. It forms the basis for performing actions such as logging in, registering, manipulating data from social networks such as Facebook, and ultimately interacting with the cloud or network. In this area, Apple provides the URLSession class as a native tool to facilitate this task. By mastering its use, developers can build more powerful and connected applications.

How to get started with URL Session in an Xcode project?

To illustrate the use of URLSession, let's create a project in Xcode called "Learning Services", including some UI elements:

  1. Add UI elements:
    • A UILabel to display information.
    • A UIActivityIndicatorView to indicate the loading of data to the user.
    • Another UILabel configured to display the status, each with its respective constraints(Constraint) to ensure correct display.

These elements will allow us to visually represent the results of consuming a web service.

How to connect outlets efficiently in Xcode?

When connecting UI elements with the code, it is recommended to create outlets manually in the ViewController. An effective way is to use the Connections Inspector to connect directly from the controller to the UI without splitting the screen, simplifying the linking process.

Example code for creating outlets:

@IBOutlet weak var nameLabel: UILabel!@IBOutlet weak var statusLabel: UILabel!@IBOutlet weak var activityIndicator: UIActivityIndicatorView!

How to handle security exceptions and endpoints?

When working with web services on iOS, it is essential to set security exceptions, as applications often restrict connections to non-HTTPS domains by default.

  1. Configure security exceptions:
    • Edit the project's info.plist file to configure allowed domains.
    • Add an XML block to define specific exceptions, ensuring that unsecured web requests are handled appropriately.

Example configuration in info.plist:

<key>NSAppTransportSecurity</key><dict> <key>NSExceptionDomains</key> <dict> <key>mymockapi.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> </dict> </dict></dict></dict> </dict></dict>
  1. Create the endpoint URL:
    • Define a guard let for the URL ensuring that it is valid before proceeding with the service call.

Example code to create the URL:

guard let endpoint = URL(string: "https://mymockapi.com/data.json") else { return }

How to consume a web service with URLSession?

Consuming web services involves configuring URLSession to make requests:

  1. Use URLSession:
    • Invoke URLSession.shared to access a shared instance.
    • Use dataTask to make the request and receive data synchronously.

Code to consume a service:

URLSession.shared.dataTask(with: endpoint) { data, response, error in if let error = error { print("There was an error:  \{ return }
 guard let data = data else { return }    
 do { if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { DispatchQueue.main.async { self.nameLabel.text = json["name"] as? String } } } catch { print("Error deserializing JSON:  \(error)") } }.resume()

What to do when the data is not updated in the UI?

If after consuming the service the UI elements do not reflect changes, you might be facing a UI update issue on the main thread. Any UI changes should be performed within the main thread using DispatchQueue.main.async.

Keep exploring and experimenting with different configurations and services! Constant practice will make you an expert in consuming web services for mobile applications.

Contributions 12

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

馃憞馃徑 las lineas de excepci贸n

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>mocky.io</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSIncludesSubdomains</key>
                <true/>
            </dict>
        </dict>
    </dict>

ESTO YA NO SE HACE AS脥

En Xcode13, a la fecha 19/05/2022, el info. plist ya no est谩, no se puede hacer la excepci贸n de seguridad como la muestra el profe.

Tenemos que a帽adir un App Transport Security Exception

  1. Para eso debemos de irnos a la configuraci贸n de nuestro proyecto (en el archivo Aprendiendo-Servicios arriba de la carpeta)
  2. Luego irnos Singing & Capabilities
  3. Le daremos al bot贸n (+) y a帽adiremos el App Transport Security Exception
  4. Ya luego solo debemos a帽adir el dominio

Con esto se ahorraran los quebraderos de cabeza y las ganas de llorar, like para que todos lo vean 鉂わ笍

// Endpoint: http://www.mocky.io/v2/5e2674472f00002800a4f417
// 1. Crear excepcion de seguridad.
// 2. Crear URL con el endpoint
// 3. Hacer request con la ayuda de URLSession
// 4. Transformar respuesta a diccionario
// 5. Ejecutar request

Me tiene bastante contento este curso

por si alguien lo necesita <https://run.mocky.io/v3/e69e76af-1159-4254-b7eb-4d8d94710696>

Al final falto agregar : **.resume() **

    URLSession.shared.dataTask(with: endpoint) { (data: Data?, _, error: Error?) in
      ...
    }.resume()

Lines just copy and paste them!

   <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key><true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>mocky.io</key>
            <dict>
                <!--Include to allow subdomains-->
                <key>NSIncludesSubdomains</key>
                <true/>
                <!--Include to allow HTTP requests-->
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>```

Puede que le ayude a alguien este link para configurar el archivo Info.plist sin editar texto.
https://stevenpcurtis.medium.com/app-transport-security-has-blocked-a-cleartext-http-http-resource-load-since-it-is-insecure-65d75b598bcc

Los que est茅n usando Xcode 13 ay cambios en la manera en la que se configura el archivo Info.plist
Les dejo un link que podr铆a ayudar
https://useyourloaf.com/blog/xcode-13-missing-info.plist/

tal vez sea debido a que no se llamo la funci贸n, ademas de que este tipo de funciones se deben de ejecutar fuera del hilo principal

Excelente clase!

Resumen