Check if an URL has got http:// prefix

后端 未结 8 761
野的像风
野的像风 2021-02-07 08:45


In my application, when the user add an object, can also add a link for this object and then the link can be opened in a webView.
I tried to save a link without http://

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 09:03

    You can use the - (BOOL)hasPrefix:(NSString *)aString method on NSString to see if an NSString containing your URL starts with the http:// prefix, and if not add the prefix.

    NSString *myURLString = @"www.google.com";
    NSURL *myURL;
    if ([myURLString.lowercaseString hasPrefix:@"http://"]) {
        myURL = [NSURL URLWithString:myURLString];
    } else {
        myURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@",myURLString]];
    }
    

    I'm currently away from my mac and can't compile/test this code, but I believe the above should work.

提交回复
热议问题