
示例:http://example.com/#blah最终应为http://example.com/
我在WebCore中发现了一些似乎通过使用CFURL功能来实现的代码,但它从未在URL中找到片段部分.我已将其封装在扩展类别中:
-(NSURL *)urlByRemovingComponent:(CFURLComponentType)component { CFRange fragRg = CFURLGetByterangeForComponent((CFURLRef)self,component,NulL); // Check to see if a fragment exists before decomposing the URL. if (fragRg.location == kcfNotFound) return self; UInt8 *urlBytes,buffer[2048]; CFIndex numBytes = CFURLGetBytes((CFURLRef)self,buffer,2048); if (numBytes == -1) { numBytes = CFURLGetBytes((CFURLRef)self,NulL,0); urlBytes = (UInt8 *)(malloc(numBytes)); CFURLGetBytes((CFURLRef)self,urlBytes,numBytes); } else urlBytes = buffer; NSURL *result = (NSURL *)CFMakeCollectable(CFURLCreateWithBytes(NulL,fragRg.location - 1,kcfStringEnCodingUTF8,NulL)); if (!result) result = (NSURL *)CFMakeCollectable(CFURLCreateWithBytes(NulL,kcfStringEnCodingISOlatin1,NulL)); if (urlBytes != buffer) free(urlBytes); return result ? [result autorelease] : self;}-(NSURL *)urlByRemovingFragment { return [self urlByRemovingComponent:kcfURLComponentFragment];} 这样使用:
NSURL *newUrl = [[NSURL URLWithString:@"http://example.com/#blah"] urlByRemovingFragment];
不幸的是,newUrl最终成为“http://example.com/#blah”因为urlByRemovingComponent中的第一行总是返回kcfNotFound
我很难过.有没有更好的方法来解决这个问题?
工作守则,感谢nall
-(NSURL *)urlByRemovingFragment { Nsstring *urlString = [self absoluteString]; // Find that last component in the string from the end to make sure to get the last one NSRange fragmentRange = [urlString rangeOfString:@"#" options:NSBackwardsSearch]; if (fragmentRange.location != NSNotFound) { // Chop the fragment. Nsstring* newURLString = [urlString substringToIndex:fragmentRange.location]; return [NSURL URLWithString:newURLString]; } else { return self; }}解决方法 这个怎么样: Nsstring* s = @"http://www.somewhere.org/foo/bar.HTML/#label";NSURL* u = [NSURL URLWithString:s];// Get the last path component from the URL. This doesn't include// any fragment.Nsstring* lastComponent = [u lastPathComponent];// Find that last component in the string from the end to make sure// to get the last oneNSRange fragmentRange = [s rangeOfString:lastComponent options:NSBackwardsSearch];// Chop the fragment.Nsstring* newURLString = [s substringToIndex:fragmentRange.location + fragmentRange.length];NSLog(@"%@",s);NSLog(@"%@",newURLString);总结
以上是内存溢出为你收集整理的cocoa – 从NSURL中删除url片段全部内容,希望文章能够帮你解决cocoa – 从NSURL中删除url片段所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)