Profanity list – Swift3

Adium pentru IOS are un plugin special pentru filtrarea cuvintelor urate – profanity list – care in schimb e foarte Objective C.
Am modelat in playground o clasa speciala de Regular Expression prin intermediul careia filtrez continutul unui dictionar. Ideea de baza este de aici

var badWordDictionary: [String : String] = [
"cuvant1" : "*******",
"cuvant2" : "*******",
"cuvant3" : "*******",
"cuvant4" : "*******",
"cuvant5" : "*******",
"cuvant6" : "*******",
]
var bannedWords = badWordDictionary.keys
var bannedPattern = bannedWords.joined(separator: "|")
var badWordPattern = "\\b(?:\(bannedPattern))\\b"

class MeetMeBadWordRegularExpression: NSRegularExpression {
override func replacementString(for result: NSTextCheckingResult, in string: String, offset: Int, template templ: String) -> String {
let matchingRange = result.range
let matchingWord = (string as NSString).substring(with: matchingRange)
if let replacedWord = badWordDictionary[matchingWord] {
return replacedWord
} else {
return "*"
}
}
}

Apoi vom folosi astfel:

var bodyMessage = "acesta este cuvant1"
let regex = try! MeetMeBadWordRegularExpression(pattern: badWordPattern, options: [])
let clearBodyMessage = regex.stringByReplacingMatches(in: bodyMessage as! String, options: [], range: NSRange(0..<(bodyMessage as! String).utf16.count), withTemplate: "") print("clean message - \(clearBodyMessage)")

Vom avea clean message - acesta este *******

Share Button

Ascunderea separatorului de 1px aflat sub UINavigationBar – Swift3

Deranjant uneori, separatorul dintre View-ul principal si UINavigationBar aparut in IOS 7 poate fi scos prin adaugarea acestui cod in AppDelegate -> application: didFinishLaunchingWithOptions:

UINavigationBar.appearance().setBackgroundImage(
UIImage(),
forBarPosition: .Any,
barMetrics: .Default)
UINavigationBar.appearance().shadowImage = UIImage()

Share Button

Utilizare XIB – cazul 2 – Views

Cea mai utilizata situatie in care sunt folosite XIB-urile este aceea a view-urilor. In aceasta situatie putem defini, configura si testa un TableViewCell – de exemplu – fara a mai incarca si restul de elemente grafice definite in Storyboard sau alte XIB-uri.
Un exemplu in acest sens:




Cum procedam?
Ca si in cazul ViewController-elor avem urmatorii pasi:

– adaugare XIB file atunci cand adaug un fisier “Cocoa Touch Class”. Se adauga fisierului .swift un fisier .xib cu acelasi nume dar continand “reprezentarea grafica” a clasei derivate.
– clasa adaugata pentru un UITableViewCell-> RequestProfileTableViewCell.swift si .xib file adaugat.
– adaugam continut in RequestProfileTableViewCell.xib si generam IBOutlet/IBAction pentru elementele din .xib in .swift
– daca este cazul -> definim continutul RequestProfileTableViewCell.swift

Din experienta mea, acest ultim pas, cel cu definire de continut este cel mai putin consistent. Foarte important e faptul ca, in prealabil, se definesc IBOutlet/IBAction pentru elementele grafice “desenate” in XIB.

Cum folosim view-ul definit XIB?

In exemplul nostru am definit un UITableViewCell.
Vom folosi acest Cell intr-un TableView atunci cand vom scrie codul pentru delegatul tableView(_:cellForRowAt:) – cam ciudatica aceasta sintaxa folosita in Swift dar cu timpul ea devine inteligibila –

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("RequestProfileTableViewCell", owner: self, options: nil)?.first as! RequestProfileTableViewCell
cell.textLabel?.text = "bubu"
return cell
}

Am bolduit modul de “import” al XIB-ului aferent unei UITableViewCell. Foarte simplu si autocomplete-ul XCode-ului ajuta daca cumva omit vre-un parametru.

Share Button

Utilizare XIB – cazul 1 – View Controller

Situatie: Storyboard-ul este prea plin. Multe ViewController-e incarcate, timp mare de asteptare atunci cand intru in storyboard pentru modificari.
Solutie: adaugare XIB file atunci cand adaug un fisier “Cocoa Touch Class”. Se adauga fisierului .swift un fisier .xib cu acelasi nume dar continand “reprezentarea grafica” a clasei derivate.
Exemplu:
– clasa adaugata pentru un UIViewController -> RequestProfileViewController.swift si .xib file adaugat.
– definim continutul RequestProfileViewController.swift
– adaugam continut in RequestProfileViewController.xib si generam IBOutlet/IBAction pentru elementele din .xib in .swift
– in clasa in care vrem sa utilizam o instanta de RequestProfileViewController trebuie sa adaugam ViewController-ul generat in .xib:

let requestProfileVC = RequestProfileViewController(nibName: "RequestProfileViewController", bundle:nil)
self.addChildViewController(requestProfileVC)
requestProfileVC.view.frame = self.view.frame
self.view.addSubview(requestProfileVC.view)
requestProfileVC.didMove(toParentViewController: self)

Utilizarea addChildViewController este explicata de Matt Neuburg excelent aici.

Share Button

UserNotifications – Swift3 – utilizare

1. Import pentru UserNotifications framework si adaugam UNUserNotificationCenterDelegate in AppDelegate.swift
2. Implementare delegatii specifici pentru UNUserNotificationCenterDelegate in ViewController-ul dedicat sau folosind o extensie:
2.1.func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
print("S-a apasat pe notificare, acum ar trebui implementantat ce anume se doreste dupa ce s-a dat click pe notificare")
}

2.2. func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("S-a primit notificare in foreground, definim aici actiunea care se va efectua in foregorund")

}
3. Cerere permisiuni de notificare din partea utilizatorului, de asemenea in AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// register user notification
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.alert, .sound]) { (granted, error) in
}
return true
}

4. Delegarea actiunilor view-ului curent catre delegatii specifici: userNotificationCenter didReceive: si userNotificationCenter willPresent
UNUserNotificationCenter.current().delegate = self
5. Adaugam Observer care va “reactiona” atunci cand selectorul va “cere” sa efectueze o notificare:
NotificationCenter.default.addObserver(self, selector: #selector(numeMetodaNotificare()), name: NSNotification.Name(rawValue: "identificatorNumeNotificare"), object: nil)
6. Implementare metoda care va genera notificare numeMetodaNotificare()
func numeMetodaNotificare(output name:String)
{
let notification = UNMutableNotificationContent()
notification.title = NSString.localizedUserNotificationString(forKey: "Request received", arguments: nil)
notification.body = NSString.localizedUserNotificationString(forKey: "Request is: \(name)!", arguments: nil)
notification.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "OneSecond", content: notification, trigger: nil)
let center = UNUserNotificationCenter.current()
print("s-a construit notificarea: \(notification.body)")
center.add(request)
}

Share Button