Search code examples
iosswiftnsunknownkeyexception

Swift - UIImage filter triggering exception


I followed an online tutorial that helps in creating a QR code. My objective is that the QR code created will be stored in Parse DB as a file and locally in a userObject as UIImage. When I ran my code below, it triggered the following error:

2015-12-06 12:43:45.994 Mawq[7246:279805] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key inputImage.'

The code to create the QR code I used is:

print("1")
let data = userObject.username!.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)
print("2")
let filter = CIFilter(name: "CIQRCodeGenerator")
print("3")
filter!.setValue(data, forKey: "QRImage")
print("4")
let newQRImage = UIImage(CIImage: filter!.outputImage!);
print("5")
user["qrCode"] = newQRImage;
print("6")
userObject.userQRCode = newQRImage;
print("7")

The print statements are just to know where the error is triggered. Apparently as shown in console, it is after line 3 prints it goes wrong. The tutorial I followed is here: http://www.appcoda.com/qr-code-generator-tutorial/.

The userObject where I want to store the image is as follows:

public class UserClass {

    var name: String?
    var email: String?
    var password: String?
    var mobile: String?
    var username: String?
    var tempToken: Int?
    var userQRCode: UIImage?
}

This is my first time to use the UIKit to achieve this outcome...so any help is appreciated.

Thanks


Solution

  • Just use the same code that was used in the tutorial:

    filter!.setValue(data, forKey: "inputMessage")
    

    while data holds the data that you want to the QR code image to hold. For example the username:

    let data = userObject.username!.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)
    

    Thats all you have to do. DO NOT change the key.

    What is used here for setting different values of the filter is called key-value-coding, you input arbitrary values for specific keys. The filter than reads values of some keys and interprets and evaluates them. The set of keys is fixed. The filter expects a inputMessage to be present. The filter however does not expect a QRImage to be passed in.