【问题标题】:UIImage Not being Set from NSDataUIImage 不是从 NSData 设置的
【发布时间】:2013-08-06 04:19:11
【问题描述】:

目标是通过将 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);

【问题讨论】:

    标签: iphone ios json


    【解决方案1】:

    假设包含 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 类别,使其使用非常方便。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      相关资源
      最近更新 更多