开发者

URL searching in iPhone program

I am a new iPhone programmer.

I am making a web based application. I'm taking the user input of a URL to a text box. When the button is pressed they will go to the web address.

Now when user type the URL such as http://www.google.com, then it works fine开发者_JAVA百科 The problem is that when user only types google.com or www.google.com it doesn't work.

I don't understand how to fix this.

If I add 'http://' problematically, I still have a problem because if the user writes the whole web address it will fail.

Here is my code for button click:

-(IBAction)go { NSMutableString *str;

    str = [NSMutableString stringWithFormat:@"http://www.%@",name.text];    
    [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];

}

Here name is a textfield and webView is an object of webView. Other than the web address behavior, it works fine.

Please help....


You are trying to create a web browser in your application??

Anyways.. a complicated for loop which checks whether the first 7 characters of you string are 'http://' or first 3 are 'www.' etc etc should do.. but how many cases are you gonna try?? i mean someone might want to open a secured link with 'https' and your code might append another http:// before it.. so make sure you have thought of all the test case before you finalize this approach...


Try this.....

-(IBAction)go {

NSMutableString *str =[[NSMutableString alloc]initWithString:name.text];

if(![str hasPrefix:@"http://www."])
{
    if([str hasPrefix:@"www."])
            [str insertString: @"http://" atIndex: 0];
    else
            [str insertString: @"http://www." atIndex: 0];

}
if(![str hasSuffix:@".com"])
{
    [str appendString:@".com"];
}
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
[str release];

}

this will check "http://" , "www." and also ".com" and handle if user did not entered any one of them.... This will work surely TRY IT......

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜