在链接中获取带有%20的JSON

时间:2014-06-18 11:20:02

标签: ios objective-c json nsurl

我有可变日期= @" 2014-06-18 12:59:46" 我做了以下事情:

NSString* formated_date = [[Constants shared].date  stringByReplacingOccurrencesOfString:@" " withString:@"%%20"];

它为我提供了新形成变量的通缉输出:" 2014-06-18%2012:59:46"。

现在,当我将所有内容放入字符串(代表网址)时,我无法从应用内获取JSON

但是,当我NSLog生成的网址,并将其复制粘贴到浏览器中时,它就可以了。 另外,如果我采用了记录的网址,并将其硬编码到json请求中,我就会按照预期获得所需的json。

到目前为止,这是我的代码:

NSString* formated_date = [[Constants shared].date  stringByReplacingOccurrencesOfString:@" " withString:@"%%20"];
NSString* url = [NSString stringWithFormat:
                 @"http://api.fessor.da.kristoffer.office/homework?rest&_rp[date]=%@&_rp[uuid]=%@&_rp[workspace]=parents&_rp[token]=%@&_rp[user_id]=%@&child_id=%@&type=parents&start_date=%@&end_date=%@",
                 formated_date,[Constants shared].uuid,[Constants shared].token,[Constants shared].user_id, [Constants shared].user_id,[Constants shared].start_date, [Constants shared].end_date
                 ];
NSLog(url);

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
    //Load the json on another thread
    [Constants shared].jsonDataHomework = [[NSData alloc] initWithContentsOfURL:
                                   [NSURL URLWithString:url"]];


    dispatch_async(dispatch_get_main_queue(), ^{

        [self getPresentHomework];            

    });

});

[self getPresentHomework]然后返回错误,因为来自json的数据是nil

我再次重复,当获取json的代码是这样时,我得到nil数据:

[Constants shared].jsonDataHomework = [[NSData alloc] initWithContentsOfURL:
                                   [NSURL URLWithString:url]];

但如果我对网址进行硬编码,那么我会得到所需的结果

[Constants shared].jsonDataHomework = [[NSData alloc] initWithContentsOfURL:
                                   [NSURL URLWithString:@"http://api.fessor.da.kristoffer.office/homework?rest&_rp[date]=2014-06-18%2012:59:46&_rp[uuid]=289A6F6F-BB71-444A-B16B-DCAF0070E1D3&_rp[workspace]=parents&_rp[token]=7fe3768108445570f11bf333cb821b0bee9213d2cced91a1f63f8c648fbc3e6a&_rp[user_id]=22066&child_id=22066&type=parents&start_date=2014-06-18&end_date=2014-06-18"]];

我做错了什么? 我应该改变线程的顺序还是类似的东西?

2 个答案:

答案 0 :(得分:2)

尝试将参数附加到网址字符串而不添加百分比,然后在将stringByAddingPercentEscapesUsingEncoding分配给NSURL之前使用NSString *urlString = [NSString stringWithFormat: @"format your url"]; NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

{{1}}

答案 1 :(得分:1)

URL字符串包含特殊字符,因此请使用

NSString *strUrl=[@"http://api.fessor.da.kristoffer.office/homework?rest&_rp[date]=2014-06-18%2012:59:46&_rp[uuid]=289A6F6F-BB71-444A-B16B-DCAF0070E1D3&_rp[workspace]=parents&_rp[token]=7fe3768108445570f11bf333cb821b0bee9213d2cced91a1f63f8c648fbc3e6a&_rp[user_id]=22066&child_id=22066&type=parents&start_date=2014-06-18&end_date=2014-06-18" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];