Asp.net web api 使用AFNetworking将对象发布到ASP.NET Web API
问题很简单,但我看到实现相当笨拙 我想将一个对象(例如设备对象)发布到web api web服务Asp.net web api 使用AFNetworking将对象发布到ASP.NET Web API,asp.net-web-api,http-post,afnetworking,Asp.net Web Api,Http Post,Afnetworking,问题很简单,但我看到实现相当笨拙 我想将一个对象(例如设备对象)发布到web api web服务 // Initialize Client AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://rezawebapi.com"]]; //Indicationg this device is online and sending its dEVICE token to th
// Initialize Client
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://rezawebapi.com"]];
//Indicationg this device is online and sending its dEVICE token to the server
Device *device = [Device new];
device.DeviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"devicetoken"];
device.IsOnline = @"True";
//updating current active users of this app in the server
NSDictionary *dictionary = [[NSDictionary alloc]initWithObjectsAndKeys:
device.DeviceToken,@"DeviceToken",
device.IsOnline,@"IsOnline",
nil];
client.parameterEncoding = AFJSONParameterEncoding;
[client postPath:@"/api/iosAppstats" parameters:dictionary success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"%@", responseObject);
// it crashes on the next line because responseObject is NSData
}failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"%@", error.localizedDescription);
}];
1-是否可以在不创建字典的情况下发送对象?(容易出错!)
2-当我的deviceToken为null时,它发送给服务器的对象为null。但是在这里考虑一个属性<代码> DeViTeCuk< /Calp>是空的,但是其他属性有它们自己的值!有人知道吗
3-我已经定义了@属性(赋值,非原子)布尔等值线代码>但是当它创建字典时EXEX-BAD-ACCESS
会上升!我应该如何定义布尔值?(我不得不将其定义为NSString。这不是一种认可的方式)1。
是否在不创建字典的情况下发送对象?(容易出错!)
您的API采用JSON。JSON只是字典、数组、字符串和数字。所以,没有。但是,它不容易出错。只需确保只将符合JSON的对象放入字典中即可。阅读更多信息
2.
当我的deviceToken为null时,它发送给服务器的对象为null。但是在这里考虑一个属性DeVICETCK是空的,但是其他属性有它们自己的值!有人知道吗
您可以有条件地添加deviceToken
,如下所示:
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"devicetoken"];
if (deviceToken) {
[dictionary setObject:deviceToken forKey:@"DeviceToken"];
}
3.
我已经定义了@property(赋值,非原子)BOOL-IsOnline;但是当它创建字典时,EXEX-BAD-ACCESS会上升!我应该如何定义布尔值?(我必须将其定义为NSString。这不是一种经批准的方式)
使用BOOL违反了我在#1:
所有对象都是NSString
、NSNumber
、NSArray
、NSDictionary
或NSNull
的实例
因此,如果您的属性是BOOL
或其他简单的数字类型,请将其包装在@()
中,使其成为NSNumber:
[dictionary setObject:@(device.IsOnline) forKey:@"DeviceToken"];
这与:
NSNumber *isOnlineNum = [NSNumber numberWithBool:device.isOnline];
[dictionary setObject:isOnlineNum forKey:@"DeviceToken"];