Attention: Application ID changes with every Appstart since iOS 8

do {
    let documentsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    let docs = try FileManager.default.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: [], options:  [.skipsHiddenFiles, .skipsSubdirectoryDescendants])
    let images = docs.filter{ $0.pathExtension == "xxx" }
    print(images)
} catch {
    print(error)
}
    //Delete Image from Notification
    if lentItems.imageURL == nil {
        //no image to delete
    } else {
        let fileManager = FileManager.default
        do {
            try fileManager.removeItem(atPath: lentItems.imageURL!)
        } catch {
            print("Could not delete Image: \(error)")
        }
    }
    do {
        let attachment = try UNNotificationAttachment(identifier: "bild", url: imageURL, options: nil)
        content.attachments = [attachment ]
    } catch {
        print("Attachment could not be loaded" )
    }
    // Create a URL
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
    let imageURL = documentsURL?.appendingPathComponent("\(String(describing: title)).png")


    // save image to URL
    if thumbnailData == nil {
        print("No Picture")
    } else {
        let notificationImage = UIImage(data: thumbnailData as! Data) // or wherever you have your UIImage
        do {
            try UIImagePNGRepresentation(notificationImage!)?.write(to: notificationImageURL!)                    
        } catch {
            print("Couldnt save image" )
        }
    }

In viewDidLoad:

//Dissmiss Keyboard
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
view.addGestureRecognizer(tap)

Function:

//Dismiss Keyboard
@objc func dismissKeyboard() {
    view.endEditing(true)
}
    //MARK: Contacts

    func checkContactsStatus() {
        let status = CNContactStore.authorizationStatus(for: .contacts)
        if status == .denied || status == .restricted {
            presentSettingsActionSheet()
            return
        }
    }

   //Ask for Contact Permissions
    func presentSettingsActionSheet() {
        let alert = UIAlertController(title: "Permission to Contacts", message: "This app needs access to contacts in order to ...", preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "Go to Settings", style: .default) { _ in
            let url = URL(string: UIApplicationOpenSettingsURLString)!
            UIApplication.shared.open(url)
        })
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        present(alert, animated: true)
    }

    func contactPicker(_ picker: CNContactPickerViewController,
                       didSelect contactProperty: CNContactProperty) {

    }

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
        // You can fetch selected name and number in the following way

        // user name
        let userName:String = contact.givenName
        let surName:String = contact.familyName
        let fullName:String = userName + " " + surName
        print(fullName)
        contactTextField.text = fullName

//         user phone number
//        let userPhoneNumbers:[CNLabeledValue<CNPhoneNumber>] = contact.phoneNumbers
//        let firstPhoneNumber:CNPhoneNumber = userPhoneNumbers[0].value

        // user phone number string
//        let primaryPhoneNumberStr:String = firstPhoneNumber.stringValue
//        print(primaryPhoneNumberStr)
    }

    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {

    }

    func chooseContact() {
        let contactPicker = CNContactPickerViewController()
        contactPicker.delegate = self
        contactPicker.displayedPropertyKeys =
            [CNContactGivenNameKey
                , CNContactPhoneNumbersKey]
        self.present(contactPicker, animated: true, completion: nil)
    }

Info.plist

<key>NSContactsUsageDescription</key>
<string>This app requires contacts access to function properly.</string>
import Foundation
import CoreData

class CoreDataStack {
    var container: NSPersistentContainer {
        let container = NSPersistentContainer(name: "todos")
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        container.loadPersistentStores { (description, error) in
            guard error == nil else {
                print("Error: \(error!)")
                return
            }
        }
        return container
    }

    var managedContext: NSManagedObjectContext {
        return container.viewContext
    }
}

If embedded in Navigation Controller:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
if let rootViewController = window?.rootViewController as? UINavigationController {
    if let viewController = rootViewController.viewControllers.first as? ViewController {
        let url = alert["imgurl"] as? NSString
        viewController.loadImage(url as String)
    }
}
}

If not embedded in Navigation Controller:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    if let rootViewController = window?.rootViewController as? ViewController {
        rootViewController.loadImage()
    }
}
let alert = UIAlertController(title: "Title", message: nil, preferredStyle: .alert)
alert.addTextField { (textField) in
        textField.placeholder = "Name"
    }

let action = UIAlertAction(title: "Save", style: .default) { (_) in 
}

let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action: UIAlertAction) in
    }

alert.addAction(action)
    alert.addAction(cancel)

present(alert, animated: true, completion: nil)

In an alert view:

 let action = UIAlertAction(title: "Update", style: .default) { (_) in

        let name = alert.textFields!.first!.text!
        let age = alert.textFields!.last!.text!


        selectedItem.setValue(name, forKey: "name")
        selectedItem.setValue(Int16(age), forKey: "age")

        do{
            try persistenceService.context.save()
        } catch {
            print("Error saving")
        }

        self.tableView.reloadData()
    }