how to pass an string value in url in iphone app

2020-05-04 10:50发布

问题:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=catId&counties-selected=Vest-Agder,Aust-Agder"]];

NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];

i have this url i want that category-selected=350 should get value from Variable how to do this I am doing but not getting result if i give var name instead of 350.

回答1:

you can try this:

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.businessfactors.de/bfcms/images/stories/videos/%@.mp4",strtext]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];


回答2:

Use NSString stringWithFormat to format the URL with the ivar:

NSString *catId = @"350";
NSString *url = [NSString stringWithFormat:@"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=%@&counties-selected=Vest-Agder,Aust-Agder", catId];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];


回答3:

for sending use stringByURLEncode, stringByURLDecode

 - (NSString *)stringByURLDecode {

        NSMutableString *tempStr = [NSMutableString stringWithString:self];
        [tempStr replaceOccurrencesOfString:@"+" withString:@" " options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];

        return [[NSString stringWithFormat:@"%@",tempStr] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    }

    - (NSString *)stringByURLEncode {

        NSMutableString *tempStr = [NSMutableString stringWithString:self];
        [tempStr replaceOccurrencesOfString:@" " withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];


        return [[NSString stringWithFormat:@"%@",tempStr] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    }