I'm trying to get a encrypted date from a web server and convert it into NSDate object. But the date formatter always returns nil date. The decrypted string does not work with the date formatter, but typing a straight date string works.
How do I debug this problem and get date formatter to parse my date?
// Decrypt the message
NSData *encrypted = [NSData dataFromBase64String:dataReturned];
NSData *decrypted = [encrypted AES128DecryptWithKey:key];
NSString *decryptedString = [[NSString alloc] initWithData:decrypted encoding:NSASCIIStringEncoding];
// decryptedString is @"2011-04-02" according to GDB
// NSString *decryptedString = @"2011-04-02"; //This works
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
[formatter setLocale:enUSPOSIXLocale];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *expiryDate = [formatter dateFromString:[decryptedString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
Well, if it works when you hardcode "2011-04-02" and it doesn't work when you think you've decrypted "2011-04-02" then obviously there's some difference between those two strings.
How about parsing and comparing both strings in code, to try and find what the difference is.
For example:
decryptedString = [decryptedString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString* goodString = @"2011-04-02";
NSLog(@"Decrypted String: %@", decryptedString);
NSLog(@"Good String: %@", goodString);
NSLog(@"Compare: %d" [goodString compare:decryptedString]); // 0 means they're identical.
NSDate* expiryDate = [formatter dateFromString:decryptedString];
NSDate* goodDate = [formatter dateFromString:goodString];
NSLog(@"Decrypted Date: %@", expiryDate);
NSLog(@"Good Date: %@", goodDate);
Run the code and look at the console output. Hopefully the problem will be a little clearer.
Don't know why the decrypted string have length of 16, whereas the good string have length of 10.
I managed to fix it by removing the control characters.
decryptedString = [decryptedString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.