Ios – -[NSConcreteMutableData base64EncodedStringWithOptions:]: unrecognized selector sent to instance 0x776e920′

iosobjective cunrecognized-selector

My app keep crashing with the following message:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteMutableData base64EncodedStringWithOptions:]: unrecognized selector sent to instance 0x776e920'

Here is part of the code. Any help will be appreciated:

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
// Saving the image in the uiimage "myImage".
UIImage *myImage = [info objectForKey:UIImagePickerControllerOriginalImage];

NSString *imageString = [self encodeToBase64String:myImage];
[self dismissViewControllerAnimated:YES completion:NULL];
}

- (NSString *)encodeToBase64String:(UIImage *)image{
    NSString * test = [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return test;
}

I have checked and the UIImage has an image in it. Thanks.

Best Answer

base64EncodedStringWithOptions: is available starting with iOS 7 and OS X 10.9.

The "unrecognized selector" exception probably means that you run the code on an earlier iOS release, where the method is not available.

There are 3rd party libraries available which offer similar methods and can be used instead if you have to support iOS 6 or 5 (for example https://github.com/nicklockwood/Base64).

The NSData documentation also states that there is a base64Encoding method (and its counterpart initWithBase64Encoding:)

Although this method was only introduced publicly for iOS 7, it has existed since iOS 4; you can use it if your application needs to target an operating system prior to iOS 7. This method behaves like base64EncodedStringWithOptions:, but ignores all unknown characters.

(So it seems that iOS had a NSData to Base64 conversion for a long time, but it was never publicly documented!)

Related Topic