Pergunta

Estou escrevendo um aplicativo de cacau, que usa nsurls - preciso remover a parte do fragmento do URL (a parte #Blah).

exemplo: http://example.com/#blah deve acabar como http://example.com/

Encontrei algum código na webcore que parece fazê -lo usando a funcionalidade CFURL, mas nunca encontra a parte do fragmento na URL. Eu o encapsulei em uma categoria de extensão:

-(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];
}

Isso é usado como tal:

NSURL *newUrl = [[NSURL URLWithString:@"http://example.com/#blah"] urlByRemovingFragment];

Infelizmente, Newurl acaba sendo "http://example.com/#blah"Porque a primeira linha em UrlbyRemovingComponent sempre retorna Kcfnotfound

Estou perplexo. Existe uma maneira melhor de fazer isso?

Código de trabalho, obrigado a 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;
    }
}
Foi útil?

Solução

Que tal agora:

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);

Outras dicas

Esta é uma pergunta bastante antiga e já foi respondida, mas para outra opção simples foi assim que eu fiz:

 NSString* urlAsString = [myURL absoluteString];
 NSArray* components = [urlAsString componentsSeparatedByString:@"#"];
 NSURL* myURLminusFragment = [NSURL URLWithString: components[0]];

Se não houver fragmento, Urlminusfragment será o mesmo que Myurl

Swift 3.0

Isso removerá o fragmento

if let fragment = url.fragment{
  url = URL(string: url.absoluteString.replacingOccurrences(of: "#\(fragment)", with: "")!
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top