UIImage to NSData for Core Data in Swift 3.0

For safe execution of code, use if-let block with Data, as function UIImagePNGRepresentation returns, optional value.

if let img = UIImage(named: "Hello.png") {
    if let data:Data = UIImagePNGRepresentation(img) {
       // Handle operations with data here...         
    }
}

Note: Data is Swift 3 class. Use Data instead of NSData with Swift 3

Generic image operations (like png & jpg both):

if let img = UIImage(named: "Hello.png") {
        if let data:Data = UIImagePNGRepresentation(img) {
               handleOperationWithData(data: data)     
        } else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
               handleOperationWithData(data: data)     
        }
}

*******
func handleOperationWithData(data: Data) {
   // Handle operations with data here...
}

By using extension:

extension UIImage {

    var pngRepresentationData: Data? {
        return UIImagePNGRepresentation(self)
    }

    var jpegRepresentationData: Data? {
        return UIImageJPEGRepresentation(self, 1.0)
    }
}

*******
if let img = UIImage(named: "Hello.png") {
      if let data = img.pngRepresentationData {
              handleOperationWithData(data: data)     
      } else if let data = img.jpegRepresentationData {
              handleOperationWithData(data: data)     
      }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
}

Try this:

if let img = UIImage(named: "hallo.png") {
    let data = UIImagePNGRepresentation(img) as NSData?
}