2015-08-20 60 views
1

想知道有無論如何我們可以修復將空格字符串轉換爲地幔中的NSURL的失敗?帶空格的字符串未能轉換爲NSURL - 地幔

我得到以下地幔錯誤:

錯誤域= MTLTransformerErrorHandlingErrorDomain代碼= 1 「無法轉換字符串URL」 的UserInfo = {0x7ff9e8de4090 = MTLTransformerErrorHandlingInputValueErrorKey YY https://x.com/dev-pub-image-md/x-img/02020-x [email protected],NSLocalizedDescription =無法轉換字符串到URL,NSLocalizedFailureReason =輸入URL字符串https://x.com/dev-pub-image-md/x-img/02020-x yy [email protected]格式錯誤}

下面的類文件;

.H -

#import "Mantle.h" 

@interface Place : MTLModel <MTLJSONSerializing> 

@property (strong, nonatomic) NSString *placeId; 
@property (strong, nonatomic) NSURL *logoURL; 

@end 

.M -

#import "Place.h" 

@implementation Place 

+ (NSDictionary *)JSONKeyPathsByPropertyKey { 
    return @{@"placeId": @"placeId", 
      @"logoURL":@"circleImage" 
      }; 
} 

+ (NSValueTransformer *)logoURLJSONTransformer { 
    return [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName]; 
} 

@end 

提前感謝!

回答

2

發生這種情況是因爲您的字符串不是URL結尾代碼(URL不能有空格)。

首先 - 使用以下方法對您的字符串進行URL編碼。來源:Stackoverflow

- (NSString *)urlencodeString:(NSString*)string { 
    NSMutableString *output = [NSMutableString string]; 
    const unsigned char *source = (const unsigned char *)[self UTF8String]; 
    int sourceLen = strlen((const char *)source); 
    for (int i = 0; i < sourceLen; ++i) { 
     const unsigned char thisChar = source[i]; 
     if (thisChar == ' '){ 
      [output appendString:@"+"]; 
     } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || 
        (thisChar >= 'a' && thisChar <= 'z') || 
        (thisChar >= 'A' && thisChar <= 'Z') || 
        (thisChar >= '0' && thisChar <= '9')) { 
      [output appendFormat:@"%c", thisChar]; 
     } else { 
      [output appendFormat:@"%%%02X", thisChar]; 
     } 
    } 
    return output; 
} 

然後將其轉換爲URL。

在您的特定場景中,您正在使用Mantle JSON變形器。所以你可以做的是;

+ (NSValueTransformer *)logoURLJSONTransformer { 
    return [MTLValueTransformer transformerUsingReversibleBlock:^id(NSString *str, BOOL *success, NSError *__autoreleasing *error) { 
     if (success) { 
      NSString *urlEncodedString = [self urlencodeString:str]; 
      return [NSURL URLWithString:urlEncodedString]; 
     }else{ 
      return @""; 
     } 

    }]; 
} 
0

你可以試試這個

NSString *baseurlString = [NSString stringWithFormat:@"your_url_here"]; 
NSString *cleanedUrl = [baseurlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]; 

然後使用此cleanedUrl爲您的工作。

相關問題