我想只拿简单的网址而不用http://

时间:2014-02-11 07:09:50

标签: objective-c

我想在代码中添加“http://”,这样用户只需键入一个简单的网址即可轻松浏览

我试过了

- (IBAction)uurl:(id)sender {
    NSURL *myurl = [NSURL URLWithString : @"http://"];
}

但它不起作用

3 个答案:

答案 0 :(得分:0)

//This is what the user types, depending on the type of input you use
NSString *urlString = @"www.bla.com"; 

NSString *httpString = @"http://";
urlString = [httpString stringByAppendingString:urlString];

//OR urlString = [NSString stringWithFormat:@"http://%@",urlString];

NSURL *url = [NSURL URLWithString:urlString];

答案 1 :(得分:0)

这很简单,但我们还需要检查用户是否自己输入了http://https://。所以请参阅下面的评论中的解释

- (IBAction)uurl:(id)sender 
{
    // Our to NSStrings that we want to be checking for.
    static NSString *httpsStr = @"https://";
    static NSString *httpStr = @"http://";

    NSString *urlStr = @"www.google.com"; // User input however you take this

    // Our check to make sure that the urlStr passed in does already have http or https
    if(![urlStr hasPrefix:httpsStr] && ![urlStr hasPrefix:httpStr]) {
        // If it doesn't have anything our default HTTP Protocol will be http
        urlStr = [NSString stringWithFormat:@"http://%@", urlStr];
    }

    // If the user has entered the http or https themselves ignore reseting to http
    // Set our urlStr as the URL we want to use.
    NSURL *url = [NSURL URLWithString:urlStr];

    // At this point you would do whatever it is you want to do with the url
}

答案 2 :(得分:0)

使用-initWithScheme:host:path:

// your user input string
NSString *userString = @"www.apple.com";

NSURL *yourURL;

if (![userString hasPrefix:@"http://"])
     yourURL = [[NSURL alloc] initWithScheme:@"http" host:userString path:@"/"];
else
     yourURL = [[NSURL alloc] initWithString:userString];