我一直在Xcode中解析JSON,如下所示:
-(void)getCheckUserData:(NSData *)data {
NSError *error;
if (!error) {
checkUserJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Uh Oh" message:@"Spaghetti-O" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
-(void) startCheckingUserLogin {
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:kCheck_user]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:20.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest
delegate:self];
if (theConnection) {
NSURL *url = [NSURL URLWithString:kCheck_user];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getCheckUserData:data];
}
}
但我雇佣了一位网络开发人员,他更新了我过时的php文件,这些文件从phpmyadmin中获取数据并用JSON编码。现在我在xcode中得到一条NSCocoaErrorDomain Code=3840消息。
以下是我从中获取数据的php文件:
<?php
require_once( 'classes/secure.php' );
$SECURE = new Secure();
if( !isset( $_POST[ 'var1' ] ) ) { exit("ERROR: no var1"); }
if( !isset( $_POST[ 'var2' ] ) ) { exit("ERROR: no var2"); }
$VARONE = $_POST[ 'var1' ];
$VARTWO = $_POST[ 'var2' ];
$RESULT = $SECURE->checkPassword( $VARONE, $VARTWO ); // Check VARONE / VARTWO
unset( $SECURE ); // Unset Secure
exit( json_encode( $RESULT ) ); // Return result as JSON string
?>
我需要更改什么?
问题在于编码。我有一个web服务99%的时间都很好,但对一个具有特定参数的端点的一个响应失败了。我在RESTClient中运行了请求,并在标题中注意到响应是ISO-8859-1,也就是Latin-1。
诀窍是将Latin-1数据转换为NSString,然后使用NSString转换回UTF8数据,以使NSJSONSerialization愉快。
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:self->receivedData options:0 error:&error];
if (!json && error && [error.domain isEqualToString:NSCocoaErrorDomain] && (error.code == NSPropertyListReadCorruptError)) {
// Encoding issue, try Latin-1
NSString *jsonString = [[NSString alloc] initWithData:self->receivedData encoding:NSISOLatin1StringEncoding];
if (jsonString) {
// Need to re-encode as UTF8 to parse, thanks Apple
json = [NSJSONSerialization JSONObjectWithData:
[jsonString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]
options:0 error:&error];
}
}
我相信有很多很棒的REST工具,你可能想看看其中的一些。RESTClient是Firefox的一个插件。