I have variable date=@"2014-06-18 12:59:46" I do the following:
NSString* formated_date = [[Constants shared].date stringByReplacingOccurrencesOfString:@" " withString:@"%%20"];
which gives me the wanted output of the new-formed variable: "2014-06-18%2012:59:46".
Now, when I put all that into string, which represents the url, I cannot fetch JSON
from within the app.
BUT, when i NSLog
the generated url, and copy paste it in browser - it works.
Also, if i take, c/p the Logged url, and hardcode it into the json request, I get the demanded json just as intended.
This is my code so far:
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]
then returns an error, since the data from the json is nil
.
I repeat once again, i get nil data when the code for fetching json is like this:
[Constants shared].jsonDataHomework = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:url]];
but if i hardcode the url, then i get the desired result
[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"]];
What am I doing wrong? Should I change the order of threads or something like that?
Try to append your parameters to the URL string without adding percentage and then use stringByAddingPercentEscapesUsingEncoding
before assigning it to your NSURL
.
NSString *urlString = [NSString stringWithFormat:
@"format your url"];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];