gpt4 book ai didi

objective-c - 无法从服务中读取 JSON

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:23:48 26 4
gpt4 key购买 nike

我正在实现忘记密码服务,我会在其中传递一个电子邮件地址,它会返回 JSON 以确认已发送的电子邮件。问题是我无法读取 json 中的响应字符串,并且我的异常消息显示数据参数为零,但如果我在我的网络浏览器中查看 url,服务看起来很好,如下所述。我的代码是:

NSURL *url = [LokalmotionCommonTask getURLForgotPassword:emailFieldTxt.text];

NSData* data = [NSData dataWithContentsOfURL: url];

@try {
NSError* error;
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data //1
options:0
error:&error];

NSLog(@"%@", [jsonDict objectForKey:@"response"]);
}
@catch (NSException *exception) {
NSLog(@"forgot password exception: %@: %@", [exception name], [exception reason]);
}

我在网络浏览器中得到的服务响应是这样的:

{"status":400,"response":"Your request to change password is already sent. Please check your email."}

异常(exception):

forgot password exception: NSInvalidArgumentException: data parameter is nil

最佳答案

在 Objective-C 中,异常仅用于 fatal error ,而不是可恢复的错误。相反,只需检查零数据:

如果您需要知道失败的原因,请使用:

NSError* error;
NSURL *url = [LokalmotionCommonTask getURLForgotPassword:emailFieldTxt.text];
NSData* data = [NSData dataWithContentsOfURL: url options:NULL error:&error];
if (data) {
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data //1
options:0
error:&error];
NSLog(@"%@", [jsonDict objectForKey:@"response"]);
}
else {
NSLog(@"forgot password error, %@", [error localizedFailureReason]);
}

存在命名约定错误:getURLForgotPassword:
以“get”开头的方法名称意味着将通过引用参数返回。最好只命名该方法:forgotPasswordURL:

这两个东西,exceptions 和 accessors 以 get 为前缀是与 Jave 的基本区别。

关于objective-c - 无法从服务中读取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10514694/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com