Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Recursos do iOS que talvez você não conheça!

Dd958da4c68b7d3227b3f1cd92a429a6?s=47 Jean Pimentel
September 03, 2016

Recursos do iOS que talvez você não conheça!

Palestra apresentada em 03/09/2016 no Digital Day BH

Animações dos slides 36, 38 e 39:
http://imgur.com/a/oWkks

Dd958da4c68b7d3227b3f1cd92a429a6?s=128

Jean Pimentel

September 03, 2016
Tweet

More Decks by Jean Pimentel

Other Decks in Technology

Transcript

  1. Recursos do iOS que talvez você não conheça!

  2. Jean Pimentel Product Engineer na CI&T Desenvolvedor mobile há 2,5

    anos Leitor de ficção científica Co-organizador do Android Meetup BH e CocoaHeads BH
  3. NSCache @available(iOS 4.0, *)

  4. NSCache - Similar a um NSDictionary - Algoritmo de expiração

    é interno, possivelmente LRU - Gerenciamento automático de memória - Chave e valor são referências - Thread-safe
  5. NSCache func objectForKey(key: AnyObject) -> AnyObject? func setObject(obj: AnyObject, forKey

    key: AnyObject) func removeObjectForKey(key: AnyObject) func removeAllObjects()
  6. NSCache let cache = NSCache() cache.setObject("Jean", forKey: "name") print(cache.objectForKey("name")) //

    Jean
  7. NSCache extension NSCache { subscript(key: AnyObject) -> AnyObject? { get

    { return objectForKey(key) } set { if let value: AnyObject = newValue { setObject(value, forKey: key) } else { removeObjectForKey(key) } } } }
  8. NSCache let cache = NSCache() cache["name"] = "Jean" print(cache["name"]) //

    Jean
  9. NSDataDetector @available(iOS 4.0, *)

  10. NSDataDetector - Subclasse de NSRegularExpression - Detecta vários tipos de

    dados: - Datas, endereços, links, telefones... - Apresenta boa precisão
  11. NSDataDetector let text = "Veja mais em: http://developer.apple.com/" let detector

    = try NSDataDetector(types: NSTextCheckingType.Link.rawValue) let match = detector.firstMatchInString(text, options: [], range: NSRange(location: 0, length: text.utf16.count)) print(match?.URL) // Optional(http://developer.apple.com/)
  12. NSDataDetector let text = "Av dos Andradas, Belo Horizonte, MG

    - 30260-070" let detector = try NSDataDetector(types: NSTextCheckingType.Address.rawValue) let match = detector.firstMatchInString(text, options: [], range: NSRange(location: 0, length: text.utf16.count)) print(match?.addressComponents) // Optional(["ZIP": "30260-070", "City": "Belo Horizonte", "State": "MG", "Street": "Av dos Andradas"])
  13. NSDataDetector let text = "contato@jeanpimentel.com.br" let detector = try NSDataDetector(types:

    NSTextCheckingType.Link.rawValue) let match = detector.firstMatchInString(text, options: [], range: NSRange(location: 0, length: text.utf16.count)) print(match?.URL) // Optional(mailto:contato@jeanpimentel.com.br)
  14. NSDataDetector extension String { func isEmail() -> Bool { guard

    let detector = NSDataDetector(types: NSTextCheckingType.Link.rawValue) else { return false } let match = detector.firstMatchInString(self, options: [], range: NSRange(location: 0, length: self.utf16.count)) return match?.URL?.scheme == "mailto" } }
  15. NSDataDetector print("josé@email.com".isEmail()) // true print("ашка@ящик.рф".isEmail()) // true

  16. CIDetector @available(iOS 5.0, *)

  17. CIDetector - Core Image, framework de manipulação de imagens -

    Detecta: - Faces (5.0, *) - Retângulos (8.0, *) - QRCode (8.0, *) - Textos (9.0, *)
  18. CIDetectorTypeFace @available(iOS 5.0, *) CIDetectorSmile, CIDetectorEyeBlink @available(iOS 7.0, *)

  19. CIDetectorTypeFace let image = UIImage(named:"example")! let ciImage = CIImage(CGImage: image.CIImage!)

    let detector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: nil) for f in detector.featuresInImage(ciImage) { guard let face = f as? CIFaceFeature else { continue } print(face.bounds) // ... }
  20. CIDetectorTypeFace

  21. CIDetectorTypeFace

  22. CIDetectorTypeFace // ... let detector = CIDetector(ofType: CIDetectorTypeFace, context: nil,

    options: nil) let options = [CIDetectorSmile: true] for f in detector.featuresInImage(image, options: options) { guard let face = f as? CIFaceFeature else { continue } print(face.bounds) // ... }
  23. CIDetectorTypeFace

  24. CIDetectorTypeFace

  25. CIFilter @available(iOS 5.0, *)

  26. CIFilter - Categorias: - Blur, ColorAdjustment, ColorEffect, CompositeOperation, DistortionEffect, Generator,

    GeometryAdjustment, Gradient, HalftoneEffect, Reduction, Sharpen, Stylize, TileEffect, Transition
  27. CIFilter

  28. CIFilter - CISepiaTone, CIColorInvert... // ... let params = ["inputImage":

    image] let filter = CIFilter(name: "CISepiaTone", withInputParameters: params) let output = UIImage(CIImage: filter!.outputImage!)
  29. CIFilter - CISepiaTone

  30. CIFilter - CIColorInvert

  31. CIFilter - CIPixellate

  32. CIFilter - CIColorMonochrome // ... let color = CIColor(red: 1.0,

    green: 0.0, blue: 0.0) let params = [ "inputImage": image, "inputColor": color ] let filter = CIFilter(name: "CIColorMonochrome", withInputParameters: params) let output = UIImage(CIImage: filter!.outputImage!)
  33. CIFilter - CIColorMonochrome

  34. UIImageView.startAnimating @available(iOS 2.0, *)

  35. UIImageView.startAnimating - "GIFs" - Lista de UIImage, frame a frame

  36. var images: [UIImage] = [] for i in 0..<8 {

    let name = String(format: "loading-%d", i) images.append(UIImage(named: name)!) } imageView.animationImages = images imageView.animationDuration = 0.8 imageView.animationRepeatCount = 0 imageView.startAnimating() UIImageView.startAnimating
  37. UIView.transitionWithView @available(iOS 4.0, *)

  38. UIView.transitionWithView label.text = " " // ... UIView.transitionWithView(label, duration: 0.5,

    options: .TransformationFlipFromLeft, animations: { label.text = " " }, completion: nil )
  39. imageView.image = UIImage(named:"empty") // ... UIView.transitionWithView(imageView, duration: 0.5, options: .TransformationCrossDisolve,

    animations: { imageView.image = UIImage(named:"full") }, completion: nil ) UIView.transitionWithView
  40. JavaScriptCore @available(iOS 7.0, *)

  41. JavaScriptCore - Wrapper no motor JavaScript do WebKit - JSContext,

    equivalente à window - JSValue, tipo dinâmico, faz a tradução - ReactNative
  42. JavaScriptCore let context = JSContext() context.evaluateScript("var sum = 1 +

    2") context.evaluateScript("var double = function(value) { return value * 2 }") let result: JSValue = context.evaluateScript("double(sum)") print(result.toInt32()) // 6
  43. JavaScriptCore context.evaluateScript("var names = ['jean', 'luiz']") let names = context.objectForKeyedSubscript("names")

    let firstName = names.objectAtIndexedSubscript(0) print(firstName.toString()) // jean
  44. JavaScriptCore context.evaluateScript("var double = function(value) { return value * 2

    }") // ... let double = context.objectForKeyedSubscript("double") let result = double.callWithArguments([5]) print(result.toInt32()) // 10
  45. JavaScriptCore context.exceptionHandler = { context, exception in print(exception) } //

    ... context.evaluateScript("var double = function(value) { return value * }") // SyntaxError: Unexpected token '}'
  46. Low Power Mode @available(iOS 9.0, *)

  47. Low Power Mode - Modo de economia de bateria -

    iOS reduz processamentos, brilho da tela, requisições em background etc - Informação pode ser obtida diretamente ou via NotificationCenter
  48. Low Power Mode if NSProcessInfo.processInfo().lowPowerModeEnabled { // evitar autoplay em

    vídeos // diminuir atualização do GPS // evitar requisições de rede // etc } else { // }
  49. Low Power Mode NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(callMe), name: NSProcessInfoPowerStateDidChangeNotification, object:

    nil )
  50. Dynamic Type @available(iOS 7.0, *)

  51. Dynamic Type - Acessibilidade - Usuário controla o tamanho das

    fonts no dispositivo - ExtraSmall - Small - Medium - Large - ExtraLarge - ExtraExtraLarge - ExtraExtraExtraLarge
  52. Dynamic Type - Atualmente existem 10 estilos - Title1 (9.0+)

    - Title2 (9.0+) - Title3 (9.0+) - Headline - Subheadline - Body - Footnote - Caption1 - Caption2 - Callout (9.0+)
  53. Dynamic Type label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) // NSNotificationCenter.defaultCenter().addObserver( self, selector: #selector(callMe),

    name: UIContentSizeCategoryDidChangeNotification, object: nil )
  54. CFStringTransform @available(iOS 2.0, *)

  55. CFStringTransform String Transform @available(iOS 9.0, *)

  56. String Transform let text = " ".stringByApplyingTransform( NSStringTransformToUnicodeName, reverse: false)

    print(text) // {SLICE OF PIZZA}
  57. String Transform let text = "Luna".stringByApplyingTransform( NSStringTransformLatinToCyrillic, reverse: false) print(text)

    // Луна
  58. String Transform let text = "您好".stringByApplyingTransform( NSStringTransformMandarinToLatin, reverse: false) print(text)

    // nín hǎo
  59. String Transform let text = "您好".stringByApplyingTransform( NSStringTransformMandarinToLatin, reverse: false) .stringByApplyingTransform(

    NSStringTransformStripDiacritics, reverse: false) print(text) // nin hao
  60. String Transform let text = "Αθήνα".stringByApplyingTransform( "Any-Latin; Latin-ASCII; Lower", reverse:

    false) print(text) // athena
  61. Obrigado! Dúvidas?

  62. Contato contato@jeanpimentel.com.br speakerdeck.com/jeanpimentel github.com/jeanpimentel