0

目标是通过将 sqlbinary 作为 JSON 发送到 iphone 的 Web 服务拉取存储为 sql server 中的 varbinary 的图像。我无法从 JSON 发送的 base64binary 设置 UIImage。我能够将二进制文件转换为 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);
4

1 回答 1

0

假设包含 base 64 编码的字符串是好的,你的代码看起来没问题。我会查看该dataFromBase64String方法,看看是否是导致问题的原因。这是我根据其他人的工作使用的版本:

-(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;
}

您可以使用此方法添加一个NSData类别,使其使用非常方便。

于 2013-08-05T20:19:11.043 回答