I'm trying to insert a base 64 image into UIImage in Objective-C I do the following:
I have the user's image into a NSURL
NSURL *url = [NSURL URLWithString: [fetchDefaults objectForKey:@"img"]];
Then I cast the url, into a NSString
NSString *string=[NSString stringWithFormat:@"%@",url];
Then I clean the string, and add the prefix "data:application/octet-stream;base64," also tried with "data:image/jpg;base64,"
NSMutableString *tempStr = [NSMutableString stringWithString:string];
[tempStr replaceOccurrencesOfString:@" " withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];
NSString *temp = [[NSString stringWithFormat:@"data:application/octet-stream;base64,%@",tempStr] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
And finally the string is cast to an NSData to be inserted into UImage
NSData *dat = [[NSData alloc]initWithBase64EncodedString:temp options:NSDataBase64DecodingIgnoreUnknownCharacters];
[avatar setImage:[UIImage imageWithData:dat]];
Despite of value of dat is not nil, when I set the image to the UIImage the image isn't showed, any idea of what am I doing wrong?
From what I understand you have your base64 string in fetchDefaults
.
/*Get base64 string*/
NSString *base64 = [fetchDefaults objectForKey:@"img"];
Use this NSData category: https://searchcode.com/codesearch/view/40028750/
/*Convert base64 to NSData object*/
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64];
/*Convert data to UIImage object*/
UIImage *image = [[UIImage alloc] initWithData:data];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.