Partage
  • Partager sur Facebook
  • Partager sur Twitter

Swift: Utilisation de Google Translate

    6 février 2019 à 12:04:00

    Bonjour,

    Je souhaiterai mettre en place un systeme de traduction de texte.

    Pour cela, je me suis base sur ce script: https://medium.com/@maximbilan/googletranslate-api-in-swift-a36489a84508

    Je n'ai toujours pas recu l'API Key (que l'on doit me fournir) donc j'essaie de prevoir le code:

        func traduction(_ str: String) {
            let currentLang = "ja"
            
            SwiftGoogleTranslate.shared.detect(str) { (detections, error) in
                if let detections = detections {
                    for detection in detections {
                        // print(detection.language)
                        SwiftGoogleTranslate.shared.translate(self, currentLang, detection.language) { (text, error) in
                            return text
                        }
                    }
                }
            }
            
        }

    Mais je crois que ca ne fonctionnera pas car j'ai l'impression que c'est de l'asynchrome.

    Existe t il un moyen de faire une requete bloquante en swift ?

    • Partager sur Facebook
    • Partager sur Twitter
      6 février 2019 à 17:06:12

      Salut,

      Ça doit effectivement être possible mais c’est une très mauvaise idée de bloquer le thread principal. J’insiste sur le très. 

      • Partager sur Facebook
      • Partager sur Twitter
        7 février 2019 à 9:23:59

        Comment ferrais tu ?

        En effet dans le callback de SwiftGoogleTranslate je ne vois pas du tout comment acceder a l'attribut "textView" car le self n'est plus le bon.

        J'ai tente de faire var _self = self (avant mon SwiftGoogleTranslate) puis dans le callback faire _self.textView

        Mais il semblerait que swift n'aime pas cette facon de faire.

        • Partager sur Facebook
        • Partager sur Twitter
          7 février 2019 à 9:39:10

          Comment ça  « le self n’est plus le bon  » ? C’est  dans le cas ou la cell est réutilisé ? Si tu scroll pas ça marche quand même ? (je comprend que c’est pas le comportement optimal mais c’est pour restreindre le problème)
          • Partager sur Facebook
          • Partager sur Twitter
            7 février 2019 à 9:52:01

            Geda a écrit:

            Comment ça  « le self n’est plus le bon  » ?

            Pardon, voici le code qu'y a par defaut:

            if let description = questionDetail.description{
                        
                        var description = description
                        
                        let attributes = [ NSAttributedString.Key.font: UIFont.init(name: "HiraginoSans-W3", size: 12)! ]
                        var attrString = NSMutableAttributedString(string: description, attributes : attributes)
                        attrString = Utils.checkMention(attributedString: attrString)
                        let style = NSMutableParagraphStyle()
                        style.lineSpacing = 2 // change line spacing between paragraph like 36 or 48
                        style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
                        let nsText = attrString.string as NSString
                        let textRange = nsText.range(of: attrString.string)
                        attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: textRange)
                        textView.attributedText = attrString
                        textView.isEditable = false
                        textView.dataDetectorTypes = .all
                        textView.isSelectable = true
                        textView.isScrollEnabled = false
                    }

            J'ai modifie ce code comme ceci :

                    if let description = questionDetail.description{
                        
                        var description = description
                        
                        if (isTranslated && questionDetail.description_translated != nil) {
                            
                            var _self = self
                            let currentLang = UserDefaults.standard.value(forKey: "lang") as! String
                            SwiftGoogleTranslate.shared.detect(description) { (detections, error) in
                                if let detections = detections {
                                    for detection in detections {
                                        SwiftGoogleTranslate.shared.translate(description, currentLang, detection.language) { (text, error) in
                                            
                                            description = text as! String
                                            
                                            let attributes = [ NSAttributedString.Key.font: UIFont.init(name: "HiraginoSans-W3", size: 12)! ]
                                            var attrString = NSMutableAttributedString(string: description, attributes : attributes)
                                            attrString = Utils.checkMention(attributedString: attrString)
                                            let style = NSMutableParagraphStyle()
                                            style.lineSpacing = 2 // change line spacing between paragraph like 36 or 48
                                            style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
                                            let nsText = attrString.string as NSString
                                            let textRange = nsText.range(of: attrString.string)
                                            attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: textRange)
                                            _self.textView.attributedText = attrString
                                            _self.textView.isEditable = false
                                            _self.textView.dataDetectorTypes = .all
                                            _self.textView.isSelectable = true
                                            _self.textView.isScrollEnabled = false
                                            
                                        }
                                    }
                                }
                            }
            
                        }
                        
                        let attributes = [ NSAttributedString.Key.font: UIFont.init(name: "HiraginoSans-W3", size: 12)! ]
                        var attrString = NSMutableAttributedString(string: description, attributes : attributes)
                        attrString = Utils.checkMention(attributedString: attrString)
                        let style = NSMutableParagraphStyle()
                        style.lineSpacing = 2 // change line spacing between paragraph like 36 or 48
                        style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
                        let nsText = attrString.string as NSString
                        let textRange = nsText.range(of: attrString.string)
                        attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: textRange)
                        textView.attributedText = attrString
                        textView.isEditable = false
                        textView.dataDetectorTypes = .all
                        textView.isSelectable = true
                        textView.isScrollEnabled = false
                    }


            Comme SwiftGoogleTranslate n'est pas bloquant, il est execute apres mais l'application semble ne pas trop aimer cette technique

            • Partager sur Facebook
            • Partager sur Twitter
              7 février 2019 à 10:33:14

              "ne pas trop aimer cette technique" :D C'est un peu flou. Et si tu fais ça, ça donne quoi ? :

              if let description = questionDetail.description, let currentLang = UserDefaults.standard.string(forKey: "lang"){
                  if isTranslated && questionDetail.description_translated != nil {
                      SwiftGoogleTranslate.shared.detect(description) {[weak textView] (detections, error) in
              
                          for detection in detections ?? [] {
               // Je ne sais pas trop ce qui est async et ce qui ne l'est pas, je duplique au pif                   SwiftGoogleTranslate.shared.translate(description, currentLang, detection.language) { [weak textView](text, error) in
                                       
                                      description = text as! String
                                       
                                      let attributes = [ NSAttributedString.Key.font: UIFont.init(name: "HiraginoSans-W3", size: 12)! ]
                                      var attrString = NSMutableAttributedString(string: text, attributes : attributes)
                                      attrString = Utils.checkMention(attributedString: attrString)
                                      let style = NSMutableParagraphStyle()
                                      style.lineSpacing = 2 // change line spacing between paragraph like 36 or 48
                                      style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
                                      let nsText = attrString.string as NSString
                                      let textRange = nsText.range(of: attrString.string)
                                      attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: textRange)
                                      textView?.attributedText = attrString
                                      textView?.isEditable = false
                                      textView?.dataDetectorTypes = .all
                                      textView?.isSelectable = true
                                      textView?.isScrollEnabled = false
                                       
                                  }
                              }
                          }
                      }
               
                  }
                   
                  let attributes = [ NSAttributedString.Key.font: UIFont.init(name: "HiraginoSans-W3", size: 12)! ]
                  var attrString = NSMutableAttributedString(string: description, attributes : attributes)
                  attrString = Utils.checkMention(attributedString: attrString)
                  let style = NSMutableParagraphStyle()
                  style.lineSpacing = 2 // change line spacing between paragraph like 36 or 48
                  style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
                  let nsText = attrString.string as NSString
                  let textRange = nsText.range(of: attrString.string)
                  attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: textRange)
                  textView.attributedText = attrString
                  textView.isEditable = false
                  textView.dataDetectorTypes = .all
                  textView.isSelectable = true
                  textView.isScrollEnabled = false
              }

              Y'a surement des erreurs de compilation, comme une accolade en trop. J'ai édité à la volée, pas simple de s'y retrouver

              -
              Edité par Geda 7 février 2019 à 10:33:41

              • Partager sur Facebook
              • Partager sur Twitter

              Swift: Utilisation de Google Translate

              × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
              × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
              • Editeur
              • Markdown