Local Notificaton not working in simulator iOS10.0 - swift3

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
askForPermission()
}
#IBAction func addLocalNotification(_ sender: AnyObject) {
addLocalNotification()
}
func addLocalNotification() {
let content = UNMutableNotificationContent()
content.title = "iOS10.0"
content.body = "Hello Buddy"
content.sound = UNNotificationSound.default()
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
// Schedule the notification.
let center = UNUserNotificationCenter.current()
center.add(request) { (error) in
print(error)
}
print("should have been added")
}
func askForPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in
}
}

You have to implement a delegate to UNUserNotificationCenter to tell the system you want to display the notification while the app is running. See the sample here: https://github.com/jerbeers/DemoLocalNotification

Related

How to show notification after close app on swift3?

I want to show notification when app close on swift 3. is it possible,
how to do it? could you advise me?
//get Data
func getData(){
let url=URL(string:"http://MyGPS/service.php")
do {
let allContactsData = try Data(contentsOf: url!)
let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : NSArray]
if let arrJSON = allContacts["mygps"] {
for index in 0...arrJSON.count-1 {
vibration.append(aObject["vibration"] as! String)
}
}
}
catch {
}
}
//show notification
func notification(){
let content = UNMutableNotificationContent()
content.title = "GPS alert message"
// content.subtitle = "Do you know?"
content.body = "Your GPS detect vibration!!"
content.badge = 1
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
// call function
func someBackgroundTask(timer:Timer) {
DispatchQueue.global(qos: DispatchQoS.background.qosClass).async {
//print("do some background task")
self.getData()
DispatchQueue.main.async {
//self.updatMarker()
}
}
}
// Use Timer
Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) {
timer in
self.someBackgroundTask(timer: timer)
}

Swift 3 Create Reminder EKEventStore

I would like to save reminders to the default reminders location. But when I press my button I get a fatal error: unexpectedly found nil while unwrapping an Optional value... I am pretty new to this and most examples I locate are overly complicated or not in Swift 3.
class ViewController: UIViewController {
var eventStore: EKEventStore?
#IBOutlet weak var reminderText: UITextField!
#IBAction func setReminder(_ sender: Any) {
let reminder = EKReminder(eventStore: self.eventStore!)
reminder.title = "Go to the store and buy milk"
reminder.calendar = (eventStore?.defaultCalendarForNewReminders())!
do {
try eventStore?.save(reminder,
commit: true)
} catch let error {
print("Reminder failed with error \(error.localizedDescription)")
}
}
}
As its a simple piece of code I thought I would post my answer after I figured it out for any future swifters. I always like simple examples.
import UIKit
import EventKit
class ViewController: UIViewController {
var eventStore = EKEventStore()
var calendars:Array<EKCalendar> = []
// Not used at this time
#IBOutlet weak var reminderText: UITextField!
#IBAction func setReminder(_ sender: Any) {
let reminder = EKReminder(eventStore: self.eventStore)
reminder.title = "Go to the store and buy milk"
reminder.calendar = eventStore.defaultCalendarForNewReminders()
do {
try eventStore.save(reminder,
commit: true)
} catch let error {
print("Reminder failed with error \(error.localizedDescription)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// get permission
eventStore.requestAccess(to: EKEntityType.reminder, completion:
{(granted, error) in
if !granted {
print("Access to store not granted")
}
})
// you need calender's permission for the reminders as they live there
calendars = eventStore.calendars(for: EKEntityType.reminder)
for calendar in calendars as [EKCalendar] {
print("Calendar = \(calendar.title)")
}
}
override func viewWillAppear(_ animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
With the #adamprocter sample, we also need to add "NSRemindersUsageDescription" key with your message in info.plist file. I tried adding this as a comment but I am not eligible.

Repeating Notifications Swift 3

I have notification that works well with only one time item. I need show my notification: 10:00 PM and 10:30 PM. How i can do that? Please tell me
My code:
NotificationManager.swift:
import UIKit
import UserNotifications
class NotificationManager
{
static let shared = NotificationManager()
let center = UNUserNotificationCenter.current()
func registerNotifications()
{
center.requestAuthorization(options: [.sound,.alert], completionHandler: {( granted, error) in })
}
func addNotificationWithCalendarTrigger(hour: Int, minute: Int)
{
let content = UNMutableNotificationContent()
content.title = "Hi"
content.body = "It,s new notification!"
content.sound = UNNotificationSound.default()
var components = DateComponents()
components.hour = hour
components.minute = minute
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: "calendar", content: content, trigger: trigger)
center.add(request) { (error) in
//handle error
}
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
timeForNotifications()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func timeForNotifications()
{
NotificationManager.shared.addNotificationWithCalendarTrigger(hour: 22, minute: 00)
}
}
might be a bit late but I think this is what you're looking for. You can set the notification to show up at 10:00 with the following code:
var components = DateComponents()
components.hour = 22
components.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: "calendar", content: content, trigger: trigger)
What I always do is replace components with date, but I think your option works as well.
var date = DateComponents()
date.hour = 22
date.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
Hope this helped you out!

transitioningDelegate never called after Segue transition

So I'm trying to implement a custom animation as my app transitions from one View Controller to another, but for some reason the animateTransition function in my custom animation class is never called.
For the record, I'm using Xcode 8 and writing in Swift 3. The problem I'm trying to over come, is that the function is never called - I'll sort out the actual animation in the future, for now its
Here is the code in my CustomPresentAnimationController class, which should handle the transition animation...
import UIKit
class CustomPresentAnimationController: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate, UINavigationControllerDelegate {
let duration = 0.5
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
print("Checking duration")
return duration
}
func animationController(forPresented presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
print("This ran 1")
return self
}
func presentationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
print("This ran 2")
return self
}
func animationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
print("This ran 3")
return self
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
print("It's working!")
guard let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) else {
return
}
guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else {
return
}
let container = transitionContext.containerView
let screenOffDown = CGAffineTransform(translationX: 0, y: -container.frame.height)
let screenOffUp = CGAffineTransform(translationX: 0, y: container.frame.height)
container.addSubview(fromView)
container.addSubview(toView)
toView.transform = screenOffUp
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: [], animations: {
fromView.transform = screenOffDown
fromView.alpha = 0.5
toView.transform = CGAffineTransform.identity
toView.alpha = 1
}) { (success) in
transitionContext.completeTransition(success)
}
}
}
Here is the code for my ViewController (which both of my View Controllers reference)...
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIViewControllerTransitioningDelegate {
override func viewDidLoad() {
if transitioningDelegate != nil {
print("Should do something...")
print(transitioningDelegate)
} else {
print("Transitioing Delegate set to nil")
}
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationController?.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
let customPresentAnimationController = CustomPresentAnimationController()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("doing our custom transition")
print(segue.destination)
let destination = segue.destination
destination.transitioningDelegate = customPresentAnimationController
}
}
When I run the code, and click on the button I provided, which links to my seance View Controller, and is set to 'Present Modally', the view changes with the standard transition (slides up from the bottom) - and the following is printed out to Xcode:
Transitioing Delegate set to nil
doing our custom transition
<moduleView.ViewController: 0x7fe427f09a40>
Should do something...
Optional(<moduleView.CustomPresentAnimationController: 0x60800002e980>)
Obviously the first line is just as the first view loads, all the rest shows that my transitionDelegate is set on the Segue destination, and is indeed loaded in as the second view loads, and that the transitionDelegate is set to CustomPresentAnimationController... yet none of the functions in that class are ever called as it never prints anything out from those functions.
Any help appreciated!
Ensure the method signature for implementing the delegate matches the updated Swift 3 syntax.

Resume Data from URLSessionDownloadTask Always nil

i have an app which i need to download the file from the internet when i downloading the file it's work good but my problem is when i pressed pause button to pause the downloading for one minute or more i get nil from resume Data
the following my code :
#IBAction func startDownloading(_ sender: UIButton)
{
isDownload = true
sessionConfig = URLSessionConfiguration.default
let operationQueue = OperationQueue.main
session = URLSession.init(configuration: sessionConfig, delegate: self, delegateQueue: operationQueue)
let url = URL(string: "www.example.com")
downloadTask = session.downloadTask(with: url!)
downloadTask.resume()
}
#IBAction func pause(_ sender: UIButton)
{
if downloadTask != nil && isDownload
{
self.downloadTask!.cancel(byProducingResumeData: { (resumeData) in
// here is the nil from the resume data
})
isDownload = false
downloadTask = nil
pasueBtnOutlet.setTitle("Resume", for: .normal)
}
if !isDownload && downloadData != nil
{
downloadTask = session.downloadTask(withResumeData: downloadData as Data)
downloadTask.resume()
isDownload = true
downloadData = nil
pasueBtnOutlet.setTitle("Pause", for: .normal)
}
}
please can help me
thanks for all
Your code seems to be correct, you just need to init the downloadData with resumeData in closure
Make a property of downloadData
var downloadData:Data!
and then in your pause button action where you cancel the task, set the downloadData with resumeData
self.downloadTask!.cancel(byProducingResumeData: { (resumeData) in
// here is the nil from the resume data
// You have to set download data with resume data
self.downloadData = resumeData
})
In order to check the progress and completion, implement these URLSessionDownloadDelegate delegates
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
print(Int(progress * 100))
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("Downloading done")
}
NOTE:- Try a valid downloadable url. For example
http://www.star.uclan.ac.uk/news_and_events/news/2010020901/sdo_resolution_comparison.png
Its http, make sure to set Transport Security in Info.plist