[英]Converting Data to string gets nil value
我正在一個項目中,我必須將圖像存儲到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.");
}
幫我謝謝你
您不能僅僅假設表示PNG圖像的二進制數據也是字符串的有效UTF-8編碼,這就是您的代碼在前兩行中所做的。
由於二進制數據無法解釋為UTF-8字符串,因此您將獲得null。
您需要做的是使用二進制數據的字符串編碼,base64是常見的,並且也由NSData
直接支持。 查找base64EncodedStringWithOptions:
方法以生成字符串,並查找initWithBase64EncodedString:options:
將編碼后的字符串轉換回數據。
高溫超導
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.