NSURLSession错误:错误的URL,在浏览器中工作

时间:2014-02-11 20:42:44

标签: ios objective-c facebook nsurlsession

我正在通过以下会话从Facebook获取帖子并找回“不好的网址”。错误。当我使用相同的URL并在浏览器中打开它时,我会回复正确的JSON帖子。我的会话有什么问题?感谢。

- (void)loadFacebookPosts
{
    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:@"https://graph.facebook.com/profileid/feed?fields=message,description,caption,name&access_token=appid|secret"]
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *error) {

                NSLog(@"error: %@", error);
                NSLog(@"data: %@", data);
                NSLog(@"response: %@", response);

            }] resume];
}

控制台:

2014-02-11 21:36:10.507 fbFetch [34365:310b] error: Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0xc7844f0 {NSUnderlyingError=0xc634c90 "bad URL", NSLocalizedDescription=bad URL}
2014-02-11 21:36:10.509 fbFetch [34365:310b] data: <>
2014-02-11 21:36:10.510 fbFetch [34365:310b] response: (null)

2 个答案:

答案 0 :(得分:3)

你有没有尝试过:

NSString *strURL = [@"https://graph.facebook.com/profileid/feed?fields=message,description,caption,name&access_token=appid|secret" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

然后使用strURL创建NSURL

答案 1 :(得分:2)

您的网址包含非法字符 - “|”所以你需要在创建URL之前使用百分比编码字符串:

NSString *URLString = @"https://graph.facebook.com/profileid/feed?fields=message,description,caption,name&access_token=appid|secret";  
NSString *escapedURLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString: escapedURLString]
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *error) {

                NSLog(@"error: %@", error);
                NSLog(@"data: %@", data);
                NSLog(@"response: %@", response);

            }] resume];