Helper Methods
Email Validation String Extension:
extension String {
var isValidEmail : Bool {
let emailFormat = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
return emailPredicate.evaluate(with: self)
}
}
Basic UIAlert:
class Alert {
class fun showBasic(title: String, message: String, vc: UIViewController) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler:nil))
vc.present(alert, animated: true)
}
}
Delegation
Create Delegate Protocol:
protocol DetailViewControllerDelegate: AnyObject {
func didFinishTask(sender: DetailViewController)
}
Add Delegate Property:
weak var delegate:DetailViewControllerDelegate?
Call Delegate Method:
delegate?.didFinishTask(self)
Adopt and implement Delegate Protocol:
extension MasterViewController: DetailViewControllerDelegate {
func didFinishTask(sender: DetailViewController) {
// do stuff like updating the UI
}
}
Remember to Set Delegate:
detailViewController.delegate = self
NotificationCenter
Add Observer:
NotificationCenter.default.addObserver(self, selector: #selector(//function(notification:)), name: //name, object: nil)
Post Notification:
NotificationCenter.default.post(name: //name, object: nil)
Remove Observers:
NotificationCenter.default.removeObserver(self)
GCD
Run on Background Thread
DispatchQueue.global(qos: .background).async{
}
Run on Main Thread
DispatchQueue.main.async{
}
HTTP Network Request
Create Request
let urlPath: String = "//URL"
let url: URL = URL(string: urlPath)!
var request: URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.timeoutInterval = 60
request.httpBody=data
request.httpShouldHandleCookies=false
Attach Data
let stringPost="//Key=Value"
let data = stringPost.data(using: String.Encoding.utf8)
URLSessionDataTask with completion handler
let session = URLSession.shared
let task: URLSessionDataTask = session.dataTask(with: request, completionHandler: {
(data, response, error) in
print("Handler")
if let respData = data {
print("Data")
print(respData)
}
if let resp = response {
print("Response")
print(resp)
}
if let err = error {
print("Error")
print(err)
}
})
task.resume())
Basic Authentication Extension
extension URLRequest {
mutating func setAuthorization(username: String, password: String) -> Bool {
let loginString = "\(username):\(password)"
guard let loginData = loginString.data(using: String.Encoding.utf8) else {
return false
}
let base64LoginString = loginData.base64EncodedString()
self.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
return true
}
}
Parse JSON
Create Decodable Struct
struct Blog: Decodable {
let title: String
let homepageURL: URL
let articles: [Article]
enum CodingKeys : String, CodingKey {
case title
case homepageURL = "home_page_url"
case articles = "items"
}
}
struct Article: Decodable {
let id: String
let url: URL
let title: String
}
Decode JSON
guard let data = data else {
print("Error: No data to decode")
return
}
guard let blog = try? JSONDecoder().decode(Blog.self, from: data) else {
print("Error: Couldn't decode data into Blog")
return
}
print("blog title: \(blog.title)")
print("blog home: \(blog.homepageURL)")
print("articles:")
for article in blog.articles {
print("- \(article.title)")
}
Manipulating Strings
Iterate Over all the Characters in a String
for character in "Dog!🐶" {
print(character)
}
Retrieve Character i in String
let str = "Hello, world!"
let index = str.index(str.startIndex, offsetBy: 4)
str[index] // returns Character 'o'
Split a String
String(str.suffix(from: index)) // returns String "o, world!"
String(str.prefix(upTo: index)) // returns String "Hell"