【问题标题】:Putting Byte value into NSDictionary [iOS]将字节值放入 NSDictionary [iOS]
【发布时间】:2013-03-31 13:11:32
【问题描述】:

我有一个发布网络服务,我需要在其中发送字节数组中的图像,并且因为我需要以 JSON 格式发送发布参数,所以我创建了它的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 对象的行中崩溃了,有什么办法可以将字节传递给NSDictionary

还有一个问题,我怎么NSLogbyteData

请帮帮我。

提前致谢!

【问题讨论】:

  • 我的回答对吗?你还不明白为什么你的应用会崩溃!!!我遇到了问题,我为二进制数据做了很多方法。实际情况是,当您尝试使用 NSDictionary 创建 JSON 对象时,所有图像都应采用特定的编码格式。否则你的应用会崩溃。
  • 您想在服务器上发布带有图像的数据,对吗?你的数据是字典形式的吗?
  • @DipenPanchasara 是的,它是字典格式,用于将字典创建为 JSON 以进行发布请求
  • @iAmbitious 我已经知道如何使用base64,但那是我不想要的,我只想要字节数组..
  • 查看@Martin R 对每个答案的评论!!!!

标签: iphone ios objective-c image bytearray


【解决方案1】:

如果您真的想将图像数据作为包含字节数的 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 相比)。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我已经转换为字节数组,我不想使用base64,因为接收器只需要字节数组中的图像..
    • 如果要在JSON文本中发送,则需要转换为base 64。否则,您可以将请求正文设置为整个图像并更改其类型。
    【解决方案3】:

    我相信您放在NSDictionary 中的任何对象本身都必须派生自NSObject

    显然Byte * 不是从NSObject 派生的。

    也许可以尝试使用集合类,例如NSArray,或者确实尝试将NSData 直接放入其中。

    【讨论】:

    • 你不能使用 NSData。 NSJSONSerialization 仅支持 NSString、NSNumber、NSArray、NSDictionary 或 NSNull。
    • 其他答案提到了 NSJSONSerialization,但 OP 没有。我很确定您可以将 NSData 放在 NSDictionary 中。谷歌提供了很多例子。
    • 是的,当然你可以把 NSData 放到 NSDictionary 里。但是JSON不支持数据对象,问题说"... post parameters in JSON format ..."
    【解决方案4】:

    您可以尝试将字节放入 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];
    

    【讨论】:

    • 这行不通。 NSJSONSerialization 仅支持 NSString、NSNumber、NSArray、NSDictionary 或 NSNull(但不支持 NSValue)。
    【解决方案5】:

    创建包含文件对象的请求字典,稍后 postWith: 函数将处理您的图像绑定任务

    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];
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 2018-01-25
      • 1970-01-01
      相关资源
      最近更新 更多