[objective-c]NSDictionaryをクエリ文字列にする
NSDictionaryをクエリ文字列にする
-(NSString*)getQueryStringByDic:(NSDictionary*)dic { NSArray*keys = [dic allKeys]; NSMutableArray*tmp=[NSMutableArray array]; for (NSString*key in keys) { [tmp addObject:[NSString stringWithFormat:@"%@=%@",key,dic[key]]]; } return [tmp componentsJoinedByString:@"&"]; } -(NSString*)getEncodedQueryStringByDic:(NSDictionary*)dic { NSArray*keys = [dic allKeys]; NSMutableArray*tmp=[NSMutableArray array]; for (NSString*key in keys) { NSString*value = dic[key]; [tmp addObject:[NSString stringWithFormat:@"%@=%@",key,[value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]] ]]; } return [tmp componentsJoinedByString:@"&"]; } -(IBAction)onTapButton:(id)sender { NSMutableDictionary*dic=[NSMutableDictionary dictionary]; dic[@"id"]=@"285"; dic[@"name"]=@"jeff"; dic[@"place"]=@"newyork"; dic[@"version"]=@"iOS7.1"; NSLog(@"%@", [self getQueryStringByDic:dic] ); }
結果
place=newyork&id=285&name=jeff&version=iOS7.1