我正在尝试将http请求发送到服务器,在其中我需要发送以下必需参数
描述:字符串,数量:浮点,发生_at:字符串,位置:字符串
由于我需要通过文本字段传递数量(其他字段通过API传递),因此Segue将PreObject对象传递到需要该数量的视图。
魔术记录用于对象
前置对象
((实体:PreObject; id:
0xd000000000040006
;
数据:{
数量=零;
creationOnBackend = 1;
货币=零;
description =“”;
费用=零;
extraInformation =“ 0xd000000001400010”;
标识符= 47;
ignoreAt = nil;
location =无;
creatededAt =“ 2017-03-12 00:00:00 +0000”;
参与者=“”;
付款人=零;
接收器=零;
状态=零;
标签=“”; }))
Http请求申请:
class func sendToBackend(object: PreObject,preObjectID: NSNumber, withCompletion completion: (error: NSError?) -> ()) {
let url = "\(ServicesUtils.baseUrl())/objects/\(preObjectID)/send"
let params = [object.dictionaryBackend()]
let sessionManager = ServicesUtils.rexpenseBaseSessionManager()
let request = sessionManager.requestSerializer.requestWithMethod("POST", URLString: url, parameters: params, error: nil)
let task = sessionManager.dataTaskWithRequest(request) { urlResponse, responseObject, error in
if let _ = error {
let returnError = ServicesUtils.rexpenseHandleErrorWithResponse(urlResponse, andRequest: request, andResult: responseObject)
completion(error: returnError)
return
}
guard let dict = responseObject as? [String: AnyObject] else {
let errorMessage = "Error"
let error = NSError(domain: "xxxxxxxxx", code: -1, userInfo: [NSLocalizedDescriptionKey : errorMessage])
completion(error: error)
return
}
let moc = NSManagedObjectContext.MR_defaultContext()
PreObject.createPreObjectwithDictionary(dict, inContext: moc)
moc.MR_saveToPersistentStoreAndWait()
completion(error: nil)
}
task.resume()
}
传递请购参数的字典:
- (NSMutableDictionary *)dictionaryBackend {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict[@"description"] = description == nil ? [NSNull null] : description;
dict[@"payer"] = @{@"id": self.payer.identifier,
@"type": @"xxxxx"};
if ([self.amount doubleValue] == [self.amount intValue]) {
NSNumber *number = [NSNumber numberWithDouble:[self.amount doubleValue] + 0.001];
dict[@"amount"] = number;
} else {
dict[@"amount"] = self.amount;
}
NSDateFormatter *dateFormatter = [ServicesUtils defaultDateFormatter];
dict[@"occurred_at"] = [dateFormatter stringFromDate:self.occuredAt];
dict[@"tags"] = [self tagsSeparatedByComma];
dict[@"location"] = self.address == nil ? [NSNull null] : self.address;
dict[@"currency"] = self.currency;
return dict;
当我点击UIButton应用崩溃时,在调试区域显示此错误:
*由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'*-[__ NSPlaceholderDictionary
initWithObjects:forKeys:count:]:尝试从中插入nil对象
对象[0]'
有人可以帮我吗?
最佳答案
崩溃通常是由于尝试创建具有nil值的字典而引起的。
在行前检查:
dict[@"payer"] = @{@"id": self.payer.identifier,
@"type": @"xxxxx"};
如果self.player.identifier为nil。
我不能建议您在nil为零时应该做什么,因为在不同的应用程序中这可能意味着不同的事情。