Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get userinfo from NSNotification in swift 3

I got this error in swift3:

Cannot convert value of type [AnyHashable : Any] to type NSDictionary in coercion.

My Code is:

  func downloadProgress(notification:NSNotification){

    if let userInfo = notification.userInfo as NSDictionary
    {
         print(userInfo) // [AnyHashable("progressPercentage"): 0.82530790852915281]

      if let progressValue = userInfo["progressPercentage"] as? Float {
        if progressValue > 0.01{

        }
      }
    }
  }

The actual userInfo value is ["progressPercentage": 0.82530790852915281] but its printed as [AnyHashable("progressPercentage"): 0.82530790852915281] and not satisfying the if condition.

Edit:

No luck for notification.userInfo as? [AnyHashable: Any], But now works for notification.userInfo as? [String: AnyObject] and notification.userInfo as? [String: Any]

enter image description here

enter image description here

like image 295
Muruganandham K Avatar asked Oct 18 '16 08:10

Muruganandham K


2 Answers

type converson

enter image description here

use

 func downloadProgress(notification:NSNotification){

if let userInfo = notification.userInfo as [String: Any] // or use if you know the type  [AnyHashable : Any]
{
     print(userInfo) 

  if let progressValue = userInfo["progressPercentage"] as? Float {
    if progressValue > 0.01{

    }
  }
}
 }

for more information see this API Reference Documents

like image 184
Anbu.Karthik Avatar answered Oct 22 '22 21:10

Anbu.Karthik


Plase use the new class Notification instead of NSNotification.

I haven't my Mac with me, but this should fix the problem.

This change is applied automatically if you use the integrated Xcode Swift conversion tool.

like image 1
Teejay Avatar answered Oct 22 '22 22:10

Teejay