gpt4 book ai didi

ios - 如何编写Json解析服务类?

转载 作者:行者123 更新时间:2023-11-29 12:17:36 26 4
gpt4 key购买 nike

我正在研究 JSON 解析,我已经实现了 JSON 服务类。但它不会接受 URL 字符串。

ServiceAPI.h

typedef enum
{
SCServiceAPITypeRegistration = 0,
SCServiceAPITypeLogin
}SCServiceAPIType;

typedef void (^ SCApiRequestCompletionHandler) (BOOL success , NSDictionary *responseDict);

@interface SCServiceAPI : NSObject
{
SCApiRequestCompletionHandler completionHandler;
}

@property (nonatomic , assign) SCServiceAPIType serviceType;
@property (nonatomic , strong) NSData *imageData;
@property (nonatomic , strong) NSData *videoData;
@property (nonatomic , strong) NSData *videoImageData;

- (void)sendAsynchronousRequest:(SCServiceAPIType)apiType
requestApiDict:(NSDictionary *)dict
completionHandler:(SCApiRequestCompletionHandler)handler;

@end

ServiceAPI.m

   #define BASE_URL =  @"https://dev.selltis.com/webservice/selltismobileservice.svc/"   


@implementation SCServiceAPI
- (void)sendAsynchronousRequest : (SCServiceAPIType )apiType requestApiDict: (NSDictionary *)dict completionHandler: (SCApiRequestCompletionHandler )handler
{
[NSURLConnection sendAsynchronousRequest:[self requestWithType:apiType withRequestData:dict] queue:[[SCGlobalDataHandler globalDataHandler] getGlobalQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError)
{
NSError *err;
NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];

NSLog(@"Response object is %@",responseObject);

if (err) {
handler(NO,responseObject); // if some coonnection error occured
}
else if ([[responseObject allKeys] containsObject:@"status"]) {

if ([[responseObject valueForKey:@"status"] integerValue] == 200) {
handler(YES,responseObject);
}
else {
handler(NO,responseObject);
}
}
}
else{
handler(NO,@{@"message":@"The network connection was lost"});
}
}];
}


- (NSURLRequest *)requestWithType:(SCServiceAPIType )serviceType withRequestData:(NSDictionary* )data
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[self urlForType:serviceType] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:180];
switch (serviceType) {
case SCServiceAPITypeRegistration:
case SCServiceAPITypeLogin:
{
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
[request setHTTPMethod:@"GET"];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:data options:0 error:nil];
NSString *jsonString = [[NSString alloc]initWithData:requestData encoding:NSUTF8StringEncoding];
[request setHTTPBody:[[NSString stringWithFormat:@"data=%@",jsonString] dataUsingEncoding:NSUTF8StringEncoding]];

return request;
}
break;
}
return request;
}

- (NSURL *)urlForType : (SCServiceAPIType )apiType
{
switch (apiType)
{
case SCServiceAPITypeRegistration:
{
return [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BASE_URL,@"registration api"]]; }
break;
case SCServiceAPITypeLogin: {
return [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",@"base api",@"registration api"]];
}
}
}

ViewController.m

- (void)loginAPI {
SCServiceAPI *serviceAPI = [[SCServiceAPI alloc] init];
// starts indicator
NSDictionary *dictRequest = [[NSDictionary alloc]initWithContentsOfURL:[NSURL URLWithString:@"https://dev.selltis.com/webservice/selltismobileservice.svc/GetDataBrowse?sUser=$$$$&sPassword=$$$$$&filename=CN&filter=LNK_RELATED_US=f01ee6a6-3bb4-4306-5553-a43a00c3c869 AND CHK_ACTIVEFIELD=1&sortorder=SYS_NAME&field=GID_ID,TXT_NAMELAST,TXT_NAMEFIRST,LNK_RELATED_CO%%TXT_COMPANYNAME,TXT_CITYBUSINESS,TXT_STATEBUSINESS&topRecord=&pageSize=100&iLinksTop=1&sAppversion=1.0.0&sAppdeviceName=<UIDevice: 0x7f9900d08530>"]];
[serviceAPI sendAsynchronousRequest:SCServiceAPITypeLogin requestApiDict:dictRequest completionHandler:^(BOOL success, NSDictionary *responseDict) {
if (success) {
dispatch_async(dispatch_get_main_queue(), ^{
// handle success
NSLog(@"%@",responseDict);
});
}
else {
dispatch_async(dispatch_get_main_queue(), ^{

// handle failure

});
}
}];
}

NSDictionary dictRequest 没有使用 URL 字符串。每次我使用 GET 方法发送字符串时,它都不起作用。你能帮我写一个 Json 解析服务类吗?

提前致谢

最佳答案

好消息是,你快到了。

坏消息 - [NSDictionary dictionaryWithContentsOfURL:] 不是那样工作的。它用于从磁盘加载 *.plist 文件。可以在这里阅读更多内容:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/#//apple_ref/occ/clm/NSDictionary/dictionaryWithContentsOfURL :

这个方法其实可以用来获取URL的内容,但是响应需要是plist格式。你在问题中提到了 JSON,所以我假设响应是 JSON 格式。

至于你眼前的问题——你根本不需要这本字典。当您发出 GET 请求时,您的所有参数都会在查询中传递。所以不需要在这个请求中添加正文数据。实际上,您传递给 NSDictionary 初始化程序的 NSURL 对象应该传递给 ServiceAPI.m 中的 NSMutableURLRequest 初始化程序


您的 - (NSURL *)urlForType : (SCServiceAPIType )apiType; 方法也有问题。您传递给 NSURL 初始化程序的字符串不是有效的 URL,并且文档声明如果它无效,则初始化程序返回 nil(https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/#//apple_ref/occ/clm/NSURL/URLWithString :)

要获得工作示例,请替换此行:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[self urlForType:serviceType] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:180];

用这两行:

NSURL *url = [NSURL URLWithString:@"your extremely long URL here"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:180];

关于ios - 如何编写Json解析服务类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31610957/

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