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!

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Publicar Tweet con video

38/52
Recursos

Aportes 4

Preguntas 0

Ordenar por:

Los aportes, preguntas y respuestas son vitales para aprender en comunidad. Regístrate o inicia sesión para participar.

Para validar ambas fuentes de contenido estoy realizando esto:

var fileData: Data = Data()
        
        if let currentVideoSavedURL = currentVideoURL,
            let videoData: Data = try? Data(contentsOf: currentVideoSavedURL)
        {
            fileData = videoData
            
        }else if let imageSaved = previewImageView.image,
            let imageSavedData: Data = imageSaved.jpegData(compressionQuality: 0.1)
        {
            fileData = imageSavedData
        }

¿Es posible realizar el “unwrapping” con guard en el mismo metodo? Me refiero a que estmos usando el bloque else para salir del “flujo”, pero en este caso, quiero continuar si el valor del video es nulo para validar el valor de la foto.

Así me quedó la función del reto:

private func uploadMedia(isCameraSource: Bool){

        // Make sure the media file exists
        guard let mediaData: Data =
                isCameraSource ?
                previewImage.image?.jpegData(compressionQuality: 0.1) :
                try? Data(contentsOf: currentVideoUrl!)
        else {
            return
        }

        SVProgressHUD.show()
        
        // Config to save media
        let metaDataConfig = StorageMetadata()

        
        // Specify content type
        metaDataConfig.contentType = isCameraSource ? "image/jpg" : "video/MP4"
        
        // Reference to storage
        let storage = Storage.storage()

        // Name the media file
        let fileName = Int.random(in: 100...1000)
        
        // Reference to bucket in Storage
        let bucketRef = storage.reference(withPath: isCameraSource ? "tweets-photos/\(fileName).jpg" : "tweets-videos/\(fileName).mp4")
        
        DispatchQueue.global(qos: .background).async {
            bucketRef.putData(mediaData, metadata: metaDataConfig) { (metadata: StorageMetadata?, error: Error?) in
              
                print("Is camera source: \(isCameraSource)")
                DispatchQueue.main.async {
                    SVProgressHUD.dismiss()
                    
                    if let error = error{
                        NotificationBanner(title: "Error",
                                           subtitle: error.localizedDescription,
                                           style: .warning).show()
                        return
                    }
                    bucketRef.downloadURL { (url: URL?,error: Error?) in
                        let downloadUrl = url?.absoluteString ?? ""
                        self.savePost(imageUrl: isCameraSource ? downloadUrl : nil, videoUrl: isCameraSource ? nil : downloadUrl)
                    }
                }
            }
            
           
            
        }
    }

Realicé de esta forma el reto

private func uploadMediaToFirebase(thereIsVideo:Bool, thereIsImage:Bool){
        
        if !thereIsVideo && thereIsImage{
            guard let currentVideoSavedUrl = currentVideoUrl,
                  let videoData:Data = try? Data(contentsOf: currentVideoSavedUrl) else {
                return
            }
            
            
            SVProgressHUD.show()
            
            let metadataConfig = StorageMetadata()
            
            metadataConfig.contentType = "video/mp4"
            
            let storageFirebase = Storage.storage()
            
            let videoName = Int.random(in: 100...1000)
            
            let folderReference = storageFirebase.reference(withPath: "videos-from-tweets/\(videoName).mp4")
            
            DispatchQueue.global(qos: .background).async {
                folderReference.putData(videoData, metadata: metadataConfig) { (metadata: StorageMetadata?, error: Error?) in
                    
                    
                    DispatchQueue.main.async {
                       
                        SVProgressHUD.dismiss()
                        if let errorFromFirebase = error{
                            NotificationBanner(title: "Error",
                                               subtitle: "\(errorFromFirebase.localizedDescription)",
                                               style: .danger).show()
                            return
                        }
                        
                       
                        folderReference.downloadURL { (url: URL?, error: Error?) in
                            let downloadUrl = url?.absoluteString ?? ""
                            self.savePost(imageURL: nil, videoURL: downloadUrl)
                        }
                    }
                }
            }
        }
        
        else if !thereIsImage && thereIsVideo{
            
            guard let imageSaved = previewImageView.image,
                  let imageSavedData:Data = imageSaved.jpegData(compressionQuality: 0.1) else {
                return
            }
            
            
            SVProgressHUD.show()
            
            let metadataConfig = StorageMetadata()
            
            metadataConfig.contentType = "image/jpg"
            
            let storageFirebase = Storage.storage()
            
            let imageName = Int.random(in: 100...1000)
            
            let folderReference = storageFirebase.reference(withPath: "phtos-from-tweets/\(imageName).jpg")
            
            DispatchQueue.global(qos: .background).async {
                folderReference.putData(imageSavedData, metadata: metadataConfig) { (metadata: StorageMetadata?, error: Error?) in
                    
                    DispatchQueue.main.async {
                       
                        SVProgressHUD.dismiss()
                        if let errorFromFirebase = error{
                            NotificationBanner(title: "Error",
                                               subtitle: "\(errorFromFirebase.localizedDescription)",
                                               style: .danger).show()
                            return
                        }
                        
                        folderReference.downloadURL { (url: URL?, error: Error?) in
                            let downloadUrl = url?.absoluteString ?? ""
                            self.savePost(imageURL: downloadUrl, videoURL: nil)
                        }
                    }
                }
            }
            
        }
        else{
            savePost(imageURL: nil, videoURL: nil)
        }
      
    }

Así quedó mi función del reto

    private func uploadMediaFileFirebase(postText: String, imageSaved: UIImage?, currentVideoURL: URL?) {

        var fileData: Data? = nil
        var contentType: String? = nil
        let fileName = Int.random(in: 100...10000)
        var filePath: String? = nil
        var isVideo: Bool = false

        //Case when is an image
        if let imageSaved = imageSaved, let imageSavedData = imageSaved.jpegData(compressionQuality: 0.1) {
            fileData = imageSavedData
            contentType = "image/jpg"
            filePath = "tweets/\(fileName).jpg"
        }

        //Case when is a video
        else if let currentVideoURL = currentVideoURL, let videoData: Data = try? Data(contentsOf: currentVideoURL) {
            fileData = videoData
            contentType = "video/mp4"
            filePath = "video-tweets/\(fileName).mp4"
            isVideo = true
        }

        guard let newFileData = fileData, let newFilePath = filePath else {
                return
        }

        SVProgressHUD.show()
        let metadataConfig = StorageMetadata()
        metadataConfig.contentType = contentType
        let storage = Storage.storage()
        let folderReference = storage.reference(withPath: newFilePath)
        DispatchQueue.global(qos: .background).async {
            folderReference.putData(newFileData, metadata: metadataConfig) { (metadata: StorageMetadata?, error: Error?) in
                if let error = error {
                    NotificationBanner(title: "Error", subtitle: error.localizedDescription, style: .warning).show()
                    return
                }
                folderReference.downloadURL { (url: URL?, error: Error?) in
                    SVProgressHUD.dismiss()
                    let finalUrl = url?.absoluteString ?? ""
                    self.savePost(postText: postText, imageUrl: isVideo ? nil : finalUrl, videoUrl: isVideo ? finalUrl : nil )
                }
            }
        }
    }