包含空格的字符串无法转换为NSURL - Mantle

时间:2015-08-20 23:18:33

标签: ios github-mantle

我想知道我们是否可以修复在Mantle中将带空格的字符串转换为NSURL失败?

我在Mantle错误之下:

错误Domain = MTLTransformerErrorHandlingErrorDomain Code = 1“无法将字符串转换为URL”UserInfo = 0x7ff9e8de4090 {MTLTransformerErrorHandlingInputValueErrorKey = https://x.com/dev-pub-image-md/x-img/02020-x yy z@2X.png,NSLocalizedDescription =无法将字符串转换为URL,NSLocalizedFailureReason =输入URL字符串https://x.com/dev-pub-image-md/x-img/02020-x yy z@2X.png格式错误}

在类文件下面;

.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 个答案:

答案 0 :(得分:2)

这是因为您的字符串未进行URL编码(URL不能包含空格)。

首先 - 使用以下方法对字符串进行URL编码。资料来源:documentation

- (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;
}

然后将其转换为网址。

在您的特定情况下,您正在使用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 @"";
        }

    }];
}

答案 1 :(得分:0)

你可以试试这个

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

然后将此cleanedUrl用于您的工作。