目前我正在使用Alamofire + ObjectMapper.我想改用AlamofireObjectMapper.但我有一个问题:如何处理api内容级错误?
例如,当我尝试保存新用户时:如果我发送到服务器的所有详细信息都有效,那么我的服务器将新用户详细信息返回为json.但如果我发送错误的细节(在应用程序逻辑级别),api将返回一个json,只显示一条错误消息,如"此用户名已被占用"
目前我正在使用Alamofire返回json:
Alamofire.request(myURL, method: .post, parameters: dic, encoding: JSONEncoding.default).validate().responseString { response in
switch response.result {
case .success:
if let JSON = response.result.value {
callback(JSON)
} else {
print("error with response.result.value")}
case .failure:
debugPrint(request)
//alert to user
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在回调中,我检查json以查看它是否看起来像用户结构或错误结构(如果它是用户结构,我使用ObjectMapper使其成为User对象):
MyAPI.saveUser(user){
(response) in
// response to json (to check error)
if (MyAPI.JSONToDictionary(response)!)["error"] != nil{
// Application level error (logic)
print((MyAPI.JSONToDictionary(response)!)["error"])
}
else{
//Using ObjectMapper - response to User object
let responsedUser = MyAPI.jsonToUser(response) …Run Code Online (Sandbox Code Playgroud) 我看到了这个问题的答案,用于将图像添加到左侧导航栏项目。我成功地做到了。
但我也想在图像旁边添加一个小文字。例如,我想显示用户有多少硬币。所以我需要显示一个硬币图像和旁边的硬币数量。怎么做到呢?
我试图设置标题(用“123”),但我只看到图像而不是标题。这是我的代码:
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "coins.png"), for: UIControlState.normal)
button.addTarget(self, action:#selector(self.callMethod), for: UIControlEvents.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
button.setTitle("123", for: UIControlState.normal)
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.leftBarButtonItem = barButton
Run Code Online (Sandbox Code Playgroud)
谢谢。