简体   繁体   中英

NSURL returning nil When Calling an API

I'm trying to call an API and bring back menu items. My string seems to contain data because when I put it into a browser, I'm getting JSON.

NSString *urlString = [NSString stringWithFormat:@"https://api.nutritionix.com/v1_1/search/subway?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY"];

NSURL *url = [NSURL URLWithString:urlString];

My "urlString" contains a lot of information, but when I put a breakpoint on the NSURL object, it says it returns "nil".

EDIT: Removed spaces however the error persists.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:urlString]];

NSHTTPURLResponse *responseCode = nil;
NSError *error = [[NSError alloc] init];


NSData *ResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];



NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:ResponseData options:kNilOptions error:nil];
itemName = dataDictionary[@"item_name"];

NSLog(@"%@", itemName);

EDIT: Added request code

Ok, I have found something interesting about your url

You just forgot about string format. Every percent sign cry to you: 'I want to be replaced with something you gain to me!'

So, to prevent such behavior, you need to hide every percent with another percent: %%

-(void)doNSURLTestOne{
    NSString *urlString = [NSString stringWithFormat:@"https://api.nutritionix.com/v1_1/search/subway?results=0%%3A20&cal_min=0&cal_max=50000&fields=item_name%%2Cbrand_name%%2Citem_id%%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY"];

    NSURL *url = [NSURL URLWithString:urlString];

    NSLog(@"is url nil? %@", url);
    NSLog(@"is urlString ok? %@", urlString);
}

But I prefer to use AFNetworking library for net part

UPD : better choice to use another clean NSString ( thanks @rmaddy )

-(void)doNSURLTestTwo{
    NSString *urlString = @"https://api.nutritionix.com/v1_1/search/subway?results=0%3A20&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Citem_id%2Cbrand_id&appId=MY_APP_ID&appKey=MY_APP_KEY";

    NSURL *url = [NSURL URLWithString:urlString];

    NSLog(@"is url nil? %@", url);
    NSLog(@"is urlString ok? %@", urlString);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM