Putting Byte value into NSDictionary [iOS]

2019-04-13 17:18发布

I have a post web service, where I need to send image in byte array, and as I need to send post parameters in JSON format, I have created its NSDictionary. My issue is how can I assign object to key in dictionary for Byte, I tried doing so and application crashes while creating NSDictionary. I am also explaining each steps with code for easy understanding of y question below :-

Here is my code for converting image to Byte format :-

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

So, now I have Byte which contain image in byte array, now I want to assign this object to NSDictionary. Here is code,

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

Now my application crashes in above line where I am creating dictJson object, is there any way I can pass Byte to NSDictionary?

Also, another question, how can I NSLog byteData?

Please help me.

Thanks in advance!

5条回答
小情绪 Triste *
2楼-- · 2019-04-13 17:42

If you'll send this information as JSON to a server, you need to convert it first to a valid string using an encoding such as Base 64.

查看更多
虎瘦雄心在
3楼-- · 2019-04-13 17:51

I believe any object you place in an NSDictionary must itself be derived from NSObject.

Clearly Byte * is not derived from NSObject.

Maybe try using a collection class that is, such as NSArray, or indeed try putting the NSData in there directly.

查看更多
smile是对你的礼貌
4楼-- · 2019-04-13 17:51

Create your Request Dictionary with File Object in it, later postWith: function will manipulate you image binding task

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

Following Function will read all your parameters from dictionary of objects you want to POST if you want to send image then add "file" key in your dictionary that identifies there is some file to be send with request

- (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);        
}
查看更多
Evening l夕情丶
5楼-- · 2019-04-13 17:53

If you really want to sent the image data as a JSON array containing the bytes as numbers, then you have to create the array "manually", there is not built-in function:

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

The JSON data would then look like

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

So perhaps that is what the server expects. But note that this is a very ineffective (in terms of space) way to send image data (compared to Base64 for example).

查看更多
一夜七次
6楼-- · 2019-04-13 18:02

You can try putting the bytes into 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];
查看更多
登录 后发表回答