UIImage(从路径)到NSData导致崩溃

时间:2015-08-24 06:25:42

标签: ios objective-c crash uiimage nsdata

我有以下代码

for (int i=0; i<self.imageArray.count; i++) 
{
    [self.operation addData:[self getDataFromImage:[self.imageArray objectAtIndex:i]] 
    forKey:[NSString stringWithFormat:@"pa_image%d",i+1] 
    mimeType:@"image/png" 
    fileName:[NSString stringWithFormat:@"pa_image%d.png",i+1]];

}

从这里开始,以下方法正在调用

-(NSData *)getDataFromImage:(UIImage *)image
{
    NSData *imageData=  UIImageJPEGRepresentation(image, 0.1);
    return imageData;
}

时,我的imageArray代码中有两种情况

1)值来自imageArray中的API,如&#34; images / upload / d872f1.png&#34;,&#34; images / upload / 0fdade.png&#34;然后在NSData中返回nil。我想从这个路径转换为NSData。怎么做?

执行此行后,我的应用程序崩溃了。它正在给予

  

由于未捕获的异常而终止应用   &#39; NSInvalidArgumentException&#39;,原因:&#39; - [__ NSCFString CGImage]:   无法识别的选择器发送到实例0x7f83a1f13510&#39;

2)当我从手机上传它的时候&#34; ,{834,1250}“。我的代码在这种情况下正常工作,转换为NSData。

有关详细信息,请参阅我的addData方法

-(void) addData:(NSData*) data forKey:(NSString*) key mimeType:(NSString*) mimeType fileName:(NSString*) fileName 
 {

  if ([self.request.HTTPMethod isEqualToString:@"GET"]) 
  {
  [self.request setHTTPMethod:@"POST"];
 }

 NSDictionary *dict = @{@"data": data,
@"name": key,
@"mimetype": mimeType,
@"filename": fileName};

[self.dataToBePosted addObject:dict];
}

2 个答案:

答案 0 :(得分:3)

Try This

for (int i=0; i<self.imageArray.count; i++) 
{
    UIImage *image;
    if([[self.imageArray objectAtIndex:i] isKindOfClass:[NSString class]]){
     image = [UIImage imageNamed:[self.imageArray objectAtIndex:i]];
    }else{
     image = [self.imageArray objectAtIndex:i];
     }
    [self.operation addData:[self getDataFromImage:image] 
forKey:[NSString stringWithFormat:@"pa_image%d",i+1] 
mimeType:@"image/png" 
fileName:[NSString stringWithFormat:@"pa_image%d.png",i+1]];

} 

答案 1 :(得分:0)

是的,用断点检查你的数组。它包含字符串而不是图像。

该例外本身就是解释性的。