简体   繁体   English

未从NSData设置UIImage

[英]UIImage Not being Set from NSData

The goal is to pull a image stored as a varbinary in a sql server through a web service that sends a sqlbinary as a JSON to an iphone. 目标是通过Web服务提取作为varbinary存储在sql服务器中的图像,该Web服务将sqlbinary作为JSON发送到iphone。 I'm having trouble setting the UIImage from the base64binary sent from the JSON. 我在从JSON发送的base64binary中设置UIImage时遇到问题。 I'm able to convert the binary to NSData but the image is not being set through the data. 我可以将二进制文件转换为NSData,但未通过数据设置图像。

for (int i = 0; i < array.count; i++) {
            NSDictionary *mealInfo = [array objectAtIndex:i];
            Meal *meal =[[Meal alloc]initWithRestaurant:[mealInfo objectForKey:@"restaurantname"]
                                               mealName:[mealInfo objectForKey:@"itemname"]
                                            description:[mealInfo objectForKey:@"itemdescription"]
                                                   Time:[mealInfo objectForKey:@"mealTime"]
                                                  price:[mealInfo objectForKey:@"itemprice"]];
            //NSString *str = @"data:image/jpg;base64,";
            //str = [str stringByAppendingString:[mealInfo objectForKey:@"itemImage"]];
            //NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];

            NSString *str = [mealInfo objectForKey:@"itemImage"];
            NSLog(@"%@", str);

            NSData *d = [[NSData alloc]initWithData:[NSData dataFromBase64String:str]];
            UIImage *image = [UIImage imageWithData:d];
            [meal setMealImage:image];

                        [meals addObject:meal];

        }
        NSLog(@"%@",[[meals objectAtIndex:0]mealPrice]);
        NSLog(@"This is how many meals %d", meals.count);

Assuming the string containing the base 64 encoded is good, your code looks OK. 假设包含以64为基数编码的字符串是好的,那么您的代码就可以了。 I would look at the dataFromBase64String method to see if that is causing the problem. 我将查看dataFromBase64String方法以查看是否是引起问题的原因。 Here is a version I use based on some else's work: 这是我根据其他工作使用的版本:

-(NSData *)dataFromBase64EncodedString:(NSString *)string{
    if (string.length > 0) {

       //the iPhone has base 64 decoding built in but not obviously. The trick is to
       //create a data url that's base 64 encoded and ask an NSData to load it.
       NSString *data64URLString = [NSString stringWithFormat:@"data:;base64,%@", string];
       NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:data64URLString]];
        return data;
    }
    return nil;
}

You could add a NSData category with this method to make its use very convenient. 您可以使用此方法添加NSData类别,以使其使用非常方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM