将数据转换为string将获得nil值
我正在一个项目中,我必须将图像存储到SQLite数据库。 但是当我尝试将NSData转换为NSString它返回nil值。
这是我的代码。
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."); }
帮助我,谢谢你
imageData = [[NSData alloc]initWithBytes:UIImagePNGRepresentation(self.img_userprofile.image).bytes length:UIImagePNGRepresentation(self.img_userprofile.image).length]; NSString *strEncodeImg = [Base64 encode:imageData];
我们从这个链接下载Base64库: https : //github.com/bborbe/base64-ios/tree/master/Base64
你不能仅仅假设表示一个PNG图像的二进制数据也是一个有效的UTF-8编码的string,这就是你的代码在前两行所做的。
由于无法将二进制数据解释为UTF-8string,因此您将收到空值。
你需要做的是使用二进制数据的string编码,base64是常见的,也直接由NSData
支持。 查找base64EncodedStringWithOptions:
方法来生成string,以及initWithBase64EncodedString:options:
将编码的string转换回数据。
HTH