You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.6 KiB

  1. // Copyright 2019 Google
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "FIRCLSURLBuilder.h"
  15. #import "FIRCLSLogger.h"
  16. @interface FIRCLSURLBuilder ()
  17. @property(nonatomic) NSMutableString *URLString;
  18. @property(nonatomic) NSUInteger queryParams;
  19. - (NSString *)escapeString:(NSString *)string;
  20. @end
  21. @implementation FIRCLSURLBuilder
  22. + (instancetype)URLWithBase:(NSString *)base {
  23. FIRCLSURLBuilder *url = [[FIRCLSURLBuilder alloc] init];
  24. [url appendComponent:base];
  25. return url;
  26. }
  27. - (instancetype)init {
  28. self = [super init];
  29. if (!self) {
  30. return nil;
  31. }
  32. _URLString = [[NSMutableString alloc] init];
  33. _queryParams = 0;
  34. return self;
  35. }
  36. - (NSString *)escapeString:(NSString *)string {
  37. #if TARGET_OS_WATCH
  38. // TODO: Question - Why does watchOS use a different encoding from the other platforms and the
  39. // Android SDK?
  40. return
  41. [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet
  42. URLPathAllowedCharacterSet]];
  43. #else
  44. return
  45. [string stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet
  46. .URLQueryAllowedCharacterSet];
  47. #endif
  48. }
  49. - (void)appendComponent:(NSString *)component {
  50. if (component.length == 0) {
  51. FIRCLSErrorLog(@"URLBuilder parameter component must not be empty");
  52. return;
  53. }
  54. [self.URLString appendString:component];
  55. }
  56. - (void)escapeAndAppendComponent:(NSString *)component {
  57. [self appendComponent:[self escapeString:component]];
  58. }
  59. - (void)appendValue:(id)value forQueryParam:(NSString *)param {
  60. if (!value) {
  61. return;
  62. }
  63. if (self.queryParams == 0) {
  64. [self appendComponent:@"?"];
  65. } else {
  66. [self appendComponent:@"&"];
  67. }
  68. self.queryParams += 1;
  69. [self appendComponent:param];
  70. [self appendComponent:@"="];
  71. if ([value isKindOfClass:NSString.class]) {
  72. [self escapeAndAppendComponent:value];
  73. } else {
  74. [self escapeAndAppendComponent:[value description]];
  75. }
  76. }
  77. - (NSURL *)URL {
  78. return [NSURL URLWithString:self.URLString];
  79. }
  80. @end