把字节值插入的NSDictionary [iOS的](Putting Byte value into

2019-08-20 16:12发布

我有一个帖子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对象,有什么办法,我可以通过字节到NSDictionary

此外,另一个问题,我怎么能NSLog byteData

请帮我。

提前致谢!

Answer 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编码为例)。



Answer 2:

如果你为JSON将该信息发送到服务器,您需要将其使用的编码转换到一个有效的字符串,如基地64 。



Answer 3:

我相信,在你将任何物体NSDictionary本身必须源自NSObject

显然, Byte *不是来源于NSObject

也许尝试使用集合类,它是如NSArray ,或者甚至可以尝试在该NSData在那里直接。



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


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


文章来源: Putting Byte value into NSDictionary [iOS]