可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 response is in following format.
I'm not able to handle this response which has 2 parts, when I tried to get the headers in didReceiveResponse: it gives the headers for the entire response whose content-type is multipart/mixed.Please show me the way to handle this response by splitting the json content and the file content.
回答1:
I also did have problems with http-multipart response. I wrote a category for NSData. Code below:
NSData+MultipartResponses.h
#import @interface NSData (MultipartResponses) - (NSArray *)multipartArray; - (NSDictionary *)multipartDictionary; @end
NSData+MultipartResponses.m
#import "NSData+MultipartResponses.h" @implementation NSData (MultipartResponses) static NSMutableDictionary *parseHeaders(const char *headers) { NSMutableDictionary *dict=[NSMutableDictionary dictionary]; int max=strlen(headers); int start=0; int cursor=0; while(cursor
回答2:
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; }