我编写了这段代码来处理字符串形式的 URL,以尝试获取可能的视网膜图像。意图是转弯
scheme://host/path/name.extension
进入
scheme://host/path/name@2x.extension
URL 是可预测的,因此假设例如只有一个“.”。在最终文件名中是安全的。但是我有那种 iOS 的感觉,我想知道这是否需要太多的代码来完成;有没有更好的,也许是 API 提供的方法来做到这一点?
这只是启动请求的方法的开始。
- (NSData *)fetchResourceWithURLLocation:(NSString *)location
requestedBy:(id<DataRequestDelegate>)requester
withIdentifier:(id)requestID {
NSData *resultData = nil;
// some disassembly to get rid of the double '/' in scheme
NSURL *locationURL = [NSURL URLWithString:location];
NSString *host = [locationURL host];
NSString *scheme = [locationURL scheme];
NSString *dataPath = [locationURL relativePath];
// if this is a retina display, rewrite the dataPath to use @2x
if ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale == 2.0)) {
NSArray *pathComponents = [dataPath componentsSeparatedByString:@"/"];
NSString *nameComponent = [pathComponents lastObject];
NSArray *nameComponents = [nameComponent componentsSeparatedByString:@"."];
NSAssert(([nameComponents count] == 2), @"nameComponent contains more than one \".\"");
nameComponent = [NSString stringWithFormat:@"%@@2x.%@", [nameComponents objectAtIndex:0], [nameComponents lastObject]];
dataPath = @"";
for(NSString *pathComponent in pathComponents) {
if(pathComponent != [pathComponents lastObject])
dataPath = [dataPath stringByAppendingString:[NSString stringWithFormat:@"%@/", pathComponent]];
}
dataPath = [dataPath stringByAppendingString:nameComponent];
}
// reassembly to check existence
NSString *processedLocation = [NSString stringWithFormat:@"%@://%@%@", scheme, host, dataPath];