문제
NSURL을 사용하는 코코아 응용 프로그램을 작성하고 있습니다. URL의 조각 부분 (#Blah 부품)을 제거해야합니다.
예시: http://example.com/#blah 끝나야합니다 http://example.com/
웹 코어에서 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);
다른 팁
이것은 꽤 오래된 질문이며 이미 답변되었지만 또 다른 간단한 옵션의 경우 이것이 내가 한 방법입니다.
NSString* urlAsString = [myURL absoluteString];
NSArray* components = [urlAsString componentsSeparatedByString:@"#"];
NSURL* myURLminusFragment = [NSURL URLWithString: components[0]];
조각이 없으면 urlminusfragment는 myurl과 동일합니다.
스위프트 3.0
이것은 조각을 제거합니다
if let fragment = url.fragment{
url = URL(string: url.absoluteString.replacingOccurrences(of: "#\(fragment)", with: "")!
}
제휴하지 않습니다 StackOverflow