此 NSURL 请求编译,但未按预期工作。我错过了什么?

This NSURL request compiles, but doesn't work as expected. What am I missing?

我目前正在学习 iOS 开发课程。我创建了一个基本的 Web 浏览器,它可以处理输入的 URL,如果用户不添加,则会添加 "http://"。使用下面的代码,用户在 textField 中输入文本,应用加载网页。

我的任务是将 textField 个带空格的条目视为 Google 个搜索。当我 运行 我的应用程序时,它会加载网页,但 Google 搜索不起作用。我不知道为什么,但我知道我可以放心这是我做错了什么。问题是什么?

属性如下:

// Properties
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, assign) BOOL isSearchTerm;

这是我写的 BOOL 来测试 textField 是 URL 还是搜索词:

// Test to determine whether textField.text is a searchTerm
- (BOOL)isSearchTerm:(UITextField *)textField {
    NSString *textInURLBar = textField.text;
    NSRange whiteSpaceRange = [textInURLBar rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
    if (whiteSpaceRange.location != NSNotFound) {
        return NO;
    } else {
        return YES;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];

    // Do a test of textField to see if it's a webpage or a search term
    if (self.isSearchTerm == YES) {
        // Homework: write code to searchGoogle, see method below
        [self searchGoogle:textField];
    } else {
        // isSearchTerm == NO, so treat as an URL
        NSString *URLString = textField.text;
        NSURL *URL = [NSURL URLWithString:URLString];

        // User enters incomplete URL
        if (!URL.scheme) {
            // if the user didn't enter http:// or https://
            URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", URLString]];
        }

        // User enters complete URL
        if (URL) {
            NSURLRequest *request = [NSURLRequest requestWithURL:URL];
            [self.webView loadRequest:request];
        }
    }
    return NO;
}

要搜索的代码 Google:

- (void)searchGoogle:(UITextField *)textField {
    NSString *URLString = textField.text;
    NSRange spaces = [URLString rangeOfString:@" "];
    NSString *searchTerm = [URLString stringByReplacingCharactersInRange:spaces withString:@"+"];
    // Google search query is http://www.google.com/search?q=
    NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?q=%@", searchTerm]];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    [self.webView loadRequest:request];
}

如果您要用 + 替换空格,您目前只在第一次出现时这样做。您可能希望对所有事件都这样做。因此,您可以使用 stringByReplacingOccurrencesOfString:withString:.

而不是 stringByReplacingCharactersInRange

或者,您可能希望对输入进行百分比转义(不仅要处理空格,还要处理其他保留字符。Web 浏览器往往会为您执行此操作,但在您自己创建请求时,您必须执行此操作在您的代码中手动。因此,至少您可以使用 stringByAddingPercentEscapesUsingEncoding(代替 stringByReplacingCharactersInRange)创建新字符串。

从技术上讲,您可能希望进一步完善 google 逻辑(执行百分比转义,将空格替换为 + 字符,但适当的百分号转义字符不会出现上述情况),您需要预置转义的字符多于 stringByAddingPercentEscapesUsingEncoding 自己执行的字符数),因此您可以对添加到 google 查询(但不添加到 URL 本身)的值执行以下百分比转义:

- (NSString *)percentEscapeString:(NSString *)string
{ 
    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)string,
                                                                                 (CFStringRef)@" ",
                                                                                 (CFStringRef)@":/?@!$&'()*+,;=",
                                                                                 kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}

它不漂亮,但我让它工作了。我取出 BOOLgoogleSearch 函数并将所有内容转储到 textFieldShouldReturn.

我不想将一堆代码转储到 textFieldShouldReturn 中,而是想将其分解为更多可重复使用的代码(有效)。虽然它有效,但我认为它很难看。

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];

    NSString *URLString = textField.text;

    // This is if it's a normal request
    if ([URLString rangeOfString:@" "].location == NSNotFound) {
        NSURL *URL = [NSURL URLWithString:URLString];

        // User enters incomplete URL
        if (!URL.scheme) {
            // if the user didn't enter http:// or https://
            URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", URLString]];
        }

        // User enters complete URL
        if (URL) {
            NSURLRequest *request = [NSURLRequest requestWithURL:URL];
            [self.webView loadRequest:request];
        }
    }

    // This handles a space in the textField.text
    if ([URLString rangeOfString:@" "].location != NSNotFound) {
        NSLog(@"there's a space in the request");
        URLString = [URLString stringByReplacingOccurrencesOfString:@" " withString:@"+"];
        NSLog(@"The new URLString is %@", URLString);
        NSURL *URL = [NSURL URLWithString:URLString];
        // User enters incomplete URL
        if (!URL.scheme) {
            // if the user didn't enter http:// or https://
            URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://google.com/search?q=%@", URLString]];
        }

        // User enters complete URL
        if (URL) {
            NSURLRequest *request = [NSURLRequest requestWithURL:URL];
            [self.webView loadRequest:request];
        }
    }
    return NO;
}