Jitendra Modi
Jitendra Modi

Reputation: 2394

Converting Data to string gets nil value

I am working on a project in which I have to store image into sqlite database. but when I try to convert NSData to NSString It returns nil value.

Here is my code.

    imageData = [[NSData alloc]initWithBytes:UIImagePNGRepresentation(self.img_userprofile.image).bytes length:UIImagePNGRepresentation(self.img_userprofile.image).length];
    NSString *charlieSendString = [[NSString alloc] initWithData:imageData encoding:NSUTF8StringEncoding];
    NSString *query = [NSString stringWithFormat:@"insert into Friends values(null, '%@', '%@', '%@')", self.txt_name.text,charlieSendString, self.txt_mobile_no.text ];
    [self.dbManager executeQuery:query];

        // If the query was successfully executed then pop the view controller.

    if (self.dbManager.affectedRows != 0) {
       NSLog(@"Query was executed successfully. Affected rows = %d", self.dbManager.affectedRows);
    }
    else{
        NSLog(@"Could not execute the query.");
    }

Help me thank you

Upvotes: 0

Views: 160

Answers (2)

CRD
CRD

Reputation: 53000

You cannot just assume that the binary data representing a PNG image is also a valid UTF-8 encoding of a string, which is what your code is doing in the first 2 lines.

You are getting null because the binary data cannot be interpreted as a UTF-8 string.

What you need to do is to use a string encoding of the binary data, base64 is common and also supported directly by NSData. Lookup up the base64EncodedStringWithOptions: method to generate the string, and initWithBase64EncodedString:options: for converting an encoded string back to data.

HTH

Upvotes: 3

Chandresh Kachariya
Chandresh Kachariya

Reputation: 677

imageData = [[NSData alloc]initWithBytes:UIImagePNGRepresentation(self.img_userprofile.image).bytes length:UIImagePNGRepresentation(self.img_userprofile.image).length];
NSString *strEncodeImg = [Base64 encode:imageData];

We have download Base64 library from this link : https://github.com/bborbe/base64-ios/tree/master/Base64

Upvotes: 0

Related Questions