ios - NSString 在 URL 中转换时被认为是 null

标签 ios null nsstring nsurl nsurlrequest

我正在尝试调用 drupal 搜索网络服务,但是当我调用它时,它说请求为空。

我在我的代码中添加了一些日志,发现 NSString 是好的,但是当我定义我的 NSURL 时,NSString 被视为 null...有人能解释一下问题是什么吗?

以下是我的代码:

- (void)FindProductsByKeyword:(NSString *)keyword :(void(^)(NSArray *produits))success
{
    __block NSArray *produits = [[NSArray alloc]init];

    NSString *fullUrl = [NSString stringWithFormat:@"%@%@?filter[title]=\%%%@\%%&filter_op[title]=LIKE", WEBSERVICES_URL, PRODUCT_DISPLAY_URL, keyword];
    NSLog(@"Appel de : %@", fullUrl);
    NSURL *URLFormatted = [NSURL URLWithString:fullUrl];
    NSLog(@"Appel de : %@", URLFormatted);
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fullUrl]];
    NSLog(@"Appel de : %@", request);

    [request setHTTPShouldHandleCookies:NO];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:
     ^(NSURLResponse * response, NSData * data, NSError * error)
     {
         NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse*)response;
         NSLog(@"status code : %d", httpResponse.statusCode);
         if(httpResponse.statusCode == 200) {
             NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
             produits = [[WebservicesService getInstance]ExtractListProduct:jsonData];
             NSLog(@"Il y a %d résultats pour la recherche", produits.count);
         }
         success(produits);
     }];
}

这是我的日志显示:

2014-01-03 17:03:51.852 mcommerce_ipad[8649:a0b] Appel de : http://domain-name.com/rest/product-display.json?filter[title]=%test%&filter_op[title]=LIKE

2014-01-03 17:03:51.852 mcommerce_ipad[8649:a0b] Appel de : (null)

2014-01-03 17:03:51.853 mcommerce_ipad[8649:a0b] Appel de : <NSMutableURLRequest: 0x8a3c9c0> { URL: (null) }

2014-01-03 17:03:51.895 mcommerce_ipad[8649:a0b] status code : 0

最后,当我直接尝试我的 NSString 时,firebug 返回了什么。

200 OK

17   Object { vid="17",   uid="0",   title="Ethylotest chimique à usage unique", more...}   

139 Object { vid="139", uid="16", title="Produit de test", more...}

142 Object { vid="142", uid="16", title="Test surface", more...}

这表明请求是正确的并且应该返回一些东西,问题来自从 NSString 到 NSURL 的转换,但我找不到它......所以请成为我的救世主!

最佳答案

正如我在评论中所说,您需要转义特殊字符,否则 URLWithString 将返回 null。

为此,请使用:

[NSURL URLWithString:[fullUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];

关于ios - NSString 在 URL 中转换时被认为是 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20945416/

相关文章:

ios - Xcode 7-'xxx'仅在iOS 8.0或更高版本上可用

java - 在返回 double java的方法中返回null

ios - NSScanner 基于最后一次出现的子字符串 "@"

objective-c - 秒表显示问题

objective-c - 如何在 Objective-C 中将 NSString 解析为 BOOL?

ios - 如何禁用 UITableViewCell 某些部分调用 DidSelect ?

ios - Objective-C 可变子类模式?

ios - 核心数据更新发生不当

python - 如何将空值存储为整数字段

swift - MailComposeViewController 错误 : unexpectedly found nil