将字节值放入NSDictionary [iOS]

时间:2013-04-09 07:52:29

标签: iphone ios objective-c image bytearray

我有一个post web服务,我需要在字节数组中发送图像,因为我需要以JSON格式发送post参数,所以我创建了它的NSDictionary。我的问题是如何将对象分配给Byte的字典中的密钥,我尝试这样做,并且在创建NSDictionary时应用程序崩溃。我还用代码解释每个步骤,以便于理解下面的问题: -

以下是将图片转换为字节格式的代码: -

NSData *data = [NSData dataWithContentsOfFile:filePath];
NSUInteger len = [data bytes];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);

所以,现在我的Byte包含字节数组中的图像,现在我想将此对象分配给NSDictionary。这是代码,

NSDictionary *dictJson = [NSDictionary dictionaryWithObjectsAndKeys:
byteData, @"photo",
nil];

现在我的应用程序崩溃在我正在创建dictJson对象的上一行,是否有任何方法可以将Byte传递给NSDictionary

另外,另一个问题是,我该如何NSLog byteData

请帮帮我。

提前致谢!

5 个答案:

答案 0 :(得分:5)

如果您确实要将图像数据作为包含字节数字的JSON数组发送, 那么你必须“手动”创建数组,没有内置函数:

NSData *data = ... // your image data
const unsigned char *bytes = [data bytes]; // no need to copy the data
NSUInteger length = [data length];
NSMutableArray *byteArray = [NSMutableArray array];
for (NSUInteger i = 0; i < length; i++) {
    [byteArray addObject:[NSNumber numberWithUnsignedChar:bytes[i]]];
}
NSDictionary *dictJson = [NSDictionary dictionaryWithObjectsAndKeys:
              byteArray, @"photo",
              nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictJson options:0 error:NULL];

JSON数据看起来像

{"photo":[byte0, byte1, byte2, ...]}

所以也许这就是服务器所期望的。但请注意,这是一种非常无效的(就空间而言)发送图像数据的方式(例如,与Base64相比)。

答案 1 :(得分:1)

如果您将此信息作为JSON发送到服务器,则需要使用Base 64等编码将其首先转换为有效字符串。

答案 2 :(得分:0)

我相信您放置在NSDictionary中的任何对象都必须来自NSObject

显然,Byte *并非来自NSObject

也许尝试使用NSArray之类的集合类,或者确实尝试将NSData直接放在那里。

答案 3 :(得分:0)

您可以尝试将字节放入NSValue:

    UIImage* testImage = [UIImage imageNamed:@"Default.png"];
    NSData* data = UIImagePNGRepresentation(testImage);
    NSValue* value = [NSValue valueWithBytes:[data bytes] objCType:@encode(UIImage)];

    NSDictionary *dictJson = [NSDictionary dictionaryWithObjectsAndKeys:
                              value, @"photo",
                              nil];

答案 4 :(得分:0)

在其中创建带有文件对象的请求字典,稍后postWith:function将操纵图像绑定任务

NSDictionary *requestDict = [NSDictionary dictionaryWithObjectsAndKeys:@"FirstObjectValue",@"FirstKey",
                             @"Second Object",@"Second Key",
                             @"myFileParameterToReadOnServerSide",@"file", nil]; // This line indicate ,POST data has file to attach
[self postWith:requestDict];

以下函数将从您想要POST的对象的字典中读取所有参数 如果你想发送图像,那么在你的字典中添加“文件”键,标识有一些文件要发送请求

- (void)postWith:(NSDictionary *)post_vars
{
    NSString *urlString = [NSString stringWithFormat:@"YourHostString"];

    NSURL *url = [NSURL URLWithString:urlString];
    NSString *boundary = @"----1010101010";

    //  define content type and add Body Boundry
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    NSEnumerator *enumerator = [post_vars keyEnumerator];
    NSString *key;
    NSString *value;
    NSString *content_disposition;

    while ((key = (NSString *)[enumerator nextObject])) {

        if ([key isEqualToString:@"file"]) {

            value = (NSString *)[post_vars objectForKey:key];
            //  ***     Write Your Image Name Here  ***
            // Covnert image to Data and bind to your post request
            NSData *postData = UIImageJPEGRepresentation([UIImage imageNamed:@"yourImage"], 1.0);

            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\";\r\nfilename=\"testUploadFile.jpg\"\r\n\r\n",value] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:postData];
        } else {
            value = (NSString *)[post_vars objectForKey:key];

            content_disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key];
            [body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];

        }

        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    }

    //Close the request body with Boundry
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:body];
    [request addValue:[NSString stringWithFormat:@"%d", body.length] forHTTPHeaderField: @"Content-Length"];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", returnString);        
}