Parse multipart response for image download in ios

前端 未结 2 1715
一整个雨季
一整个雨季 2020-12-03 19:53

In my application, I\'m downloading image from server as multipart content. In my response data I\'m getting 2 parts: one is json content and other is downloaded file. The r

2条回答
  •  攒了一身酷
    2020-12-03 20:32

    For me, your code didn't work. Instead, I rewrote that code in pure objective-c: Take care that (my) boundaries in this code always have additional -- in front of the next boundary and a final boundary - those are stripped. An NSArray is returned with a NSDictionary for each part, containing the keys "headers" as NSDictionary and "body" as NSData

    - (NSArray *)multipartArrayWithBoundary:(NSString *)boundary
    {
        NSString *data = [[[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding] autorelease];
    
        NSArray *multiparts = [data componentsSeparatedByString:[@"--" stringByAppendingString:boundary]]; // remove boundaries
        multiparts = [multiparts subarrayWithRange:NSMakeRange(1, [multiparts count]-2)]; // continued removing of boundaries
    
        NSMutableArray *toReturn = [NSMutableArray arrayWithCapacity:2];
        for(NSString *part in multiparts)
        {
            part = [part stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            NSArray *separated = [part componentsSeparatedByString:@"\n\n"];
    
            NSMutableDictionary *headers = [NSMutableDictionary dictionaryWithCapacity:3];
            for(NSString *headerLine in [[separated objectAtIndex:0] componentsSeparatedByString:@"\n"])
            {
                NSArray *keyVal = [headerLine componentsSeparatedByString:@":"];
    
                [headers setObject:[[keyVal objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:[[keyVal objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
            }
    
            [toReturn addObject:[NSDictionary dictionaryWithObjectsAndKeys:[[separated objectAtIndex:1] dataUsingEncoding:NSUTF8StringEncoding], @"body", headers, @"headers", nil]];
        }
    
        return toReturn;
    }
    

提交回复
热议问题