gpt4 book ai didi

cocoa - 从 NSURL 中删除 url 片段

转载 作者:行者123 更新时间:2023-12-03 16:07:31 26 4
gpt4 key购买 nike

我正在编写一个使用 NSURL 的 Cocoa 应用程序——我需要删除 URL 的片段部分(#BLAH 部分)。

示例: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, urlBytes, fragRg.location - 1, kCFStringEncodingUTF8, NULL));
if (!result)
result = (NSURL *)CFMakeCollectable(CFURLCreateWithBytes(NULL, urlBytes, fragRg.location - 1, 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 one
NSRange fragmentRange = [s rangeOfString:lastComponent
options:NSBackwardsSearch];

// Chop the fragment.
NSString* newURLString = [s substringToIndex:fragmentRange.location + fragmentRange.length];

NSLog(@"%@", s);
NSLog(@"%@", newURLString);

关于cocoa - 从 NSURL 中删除 url 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1682919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com