BAD URL错误,因为我从24小时变为上午/下午

时间:2014-07-20 08:53:34

标签: ios nsdateformatter

2014-07-20 09:29:22.561 EE[4636:60b] Ticket/3B0281/33/2014-07-20T10:00 am:00
2014-07-20 09:29:22.625 EE[4636:60b] Request Failed with Error: Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x15ed01a0 {NSUnderlyingError=0x15e99620 "bad URL", NSLocalizedDescription=bad URL}

从此:

[formatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"];
        NSDate *alertTime = [formatter dateFromString:str];
        //NSDate *alertTime = [[NSDate date] dateByAddingTimeInterval:60];

[formatter setDateFormat:@"dd-MM-yyyy h:mm:ss a"];
        NSDate *alertTime = [formatter dateFromString:str];
        //NSDate *alertTime = [[NSDate date] dateByAddingTimeInterval:60];

从24小时变为上午/下午后,我收到了上述错误消息,请问在这种情况下我做错了什么?

根据@skrew建议,这是我在代码中使用的内容:

    static NSString AFPercentEscapedQueryStringPairMemberFromStringWithEncoding(NSString   *string, NSStringEncoding encoding) {
// Escape characters that are legal in URIs, but have unintentional semantic significance when used in a query string parameter
static NSString * const kAFLegalCharactersToBeEscaped = @":/.?&=;+!@$()~";

return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,   (CFStringRef)string, NULL, (CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) autorelease];
}

1 个答案:

答案 0 :(得分:1)

您必须对URL进行编码,因为您现在有一个空格(上午10:00)

添加NSString + URLEncoding.h:

- (NSString *)urlEncode;

添加NSString + URLEncoding.m:

- (NSString *)urlEncode
{
    return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                            (__bridge CFStringRef)self,
                                                                            NULL,
                                                                            (CFStringRef)@"!*'();:@&=+$,/?%#[] ",
                                                                            kCFStringEncodingUTF8);
}

在您的代码中,构建网址时,请添加:

NSString *url = [url urlEncode];

如果你不想要上面的所有代码,可以使用quickfix(但不推荐)来替换url中的空格

url = [url stringByReplacingOccurrencesOfString: @" " withString: @"%20"];