實(shí)現(xiàn)斷點(diǎn)下載和后臺(tái)下載過(guò)程中睦刃,用到最多的是叫resumeData的東西不瓶,變化多端棚放,神出鬼沒(méi)枚粘,想要了解這個(gè)變化的可以參考這位大神的文章,http://www.reibang.com/p/da565e14ef88飘蚯,在仿寫(xiě)OC版輪子的過(guò)程中發(fā)現(xiàn)一個(gè)問(wèn)題:上面那位大神由于采用的是swift語(yǔ)言馍迄,在解析resumeData過(guò)程中福也,用到下面這段代碼
internal class func getResumeDictionary(_data:Data) ->NSMutableDictionary? {
varresumeDictionary:NSMutableDictionary?
if#available(OSX10.11,iOS9.0, *) {
letkeyedUnarchiver =NSKeyedUnarchiver(forReadingWith: data)
do{
resumeDictionary =trykeyedUnarchiver.decodeTopLevelObject(of:NSMutableDictionary.self, forKey:"NSKeyedArchiveRootObjectKey") ??nil
ifresumeDictionary ==nil{
resumeDictionary =trykeyedUnarchiver.decodeTopLevelObject(of:NSMutableDictionary.self, forKey:NSKeyedArchiveRootObjectKey)
}
}catch{}
keyedUnarchiver.finishDecoding()
}
ifresumeDictionary ==nil{
do{
resumeDictionary =try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.ReadOptions(), format: nil) as? NSMutableDictionary
}catch{}
}
return resumeDictionary
}
注意這行代碼:
keyedUnarchiver.decodeTopLevelObject(of: NSMutableDictionary.self, forKey: "NSKeyedArchiveRootObjectKey") ?? nil
點(diǎn)進(jìn)去看看:
@available(OSX 10.11, iOS 9.0, *)
public func decodeTopLevelObject<DecodedObjectType>(of cls: DecodedObjectType.Type, forKey key: String) throws -> DecodedObjectType? where DecodedObjectType : NSObject, DecodedObjectType : NSCoding
根據(jù)傳入的類(lèi)型,查找NSKeyedArchiveRootObjectKey根鍵攀圈,解析為相應(yīng)類(lèi)型拟杉,最后得到一個(gè)key-value的字典,里面是這個(gè)信息:
從這里可以拿到你可能想要的信息量承,接收量搬设、臨時(shí)文件的名稱(chēng)等等信息,但在oc中蒙圈了撕捍,試了好幾種方法拿穴,都無(wú)法解析出這個(gè)字典。
根據(jù)錯(cuò)誤信息的反饋忧风,最后找到了解決辦法:
//將resumeData解析成字典
+ (NSMutableDictionary *)getResumeDictionary:(NSData *)data{
NSMutableDictionary *resumeDictionary = [NSMutableDictionary dictionary];
NSError *error;
if (@available(iOS 9.0,*)) {
id keyUnarchiver = [[NSKeyedUnarchiver alloc]initForReadingFromData:data error:&error];
@try {
NSError *decodeError1;
NSSet *typeSet = [NSSet setWithObjects:[NSDictionary class],[NSMutableData class],nil];
resumeDictionary = [keyUnarchiver decodeTopLevelObjectOfClasses:typeSet forKey:@"NSKeyedArchiveRootObjectKey" error:&decodeError1];
if (resumeDictionary == nil) {
resumeDictionary = [keyUnarchiver decodeTopLevelObjectOfClasses:typeSet forKey:NSKeyedArchiveRootObjectKey error:&decodeError1];
}
} @catch (NSException *exception) {
}
[keyUnarchiver finishDecoding];
}
return resumeDictionary;
}
resumeData根鍵為一個(gè)字典類(lèi)型默色,再往里走一層為NSMutableData類(lèi)型,只要將對(duì)應(yīng)的解析類(lèi)型傳入狮腿,最后就能完整的解析出想要的結(jié)果腿宰,這是我對(duì)這個(gè)方法的理解,第一次發(fā)文缘厢,不對(duì)請(qǐng)指正吃度。