I use Alamofire Network request,want to handling error messages,
My code :
class NetWorkingEngine: NSObject {
typealias CreateNetWorkBlockSuccess = (_ responseobject:Any) -> ();
typealias CreateNetWorkBlockFail = (_ responseobject:NSDictionary) -> ();
func getDataFun(URL:String,netWorkingBlockSuccess:@escaping CreateNetWorkBlockSuccess,netWorkingBlockField:@escaping CreateNetWorkBlockField) -> Void {
Alamofire.request(URL).responseJSON { (responseObject) in
if responseObject.result.isSuccess {
netWorkingBlockSuccess(responseObject.data!);
}else{
netWorkingBlockFail(responseObject.result);
}
}
}
}
But in line
netWorkingBlockFail(responseObject.result)
error
cannot convert value of type “Result<Any>” to expected argument type "NSDictionary"
what should I do?
update:
I want to resquert Error Info, if you error request,Error info is 'Any',But how to 'Error info' convert Dictionary?
You can convert Any type to Dictionary using [:] type. Suppose you have a variable called person
which is of type Any; then use the following code:
let personDictionary = (person as! [String:String])["name"]
...where name
is the key in the dictionary.
You can only convert something to a Dictionary if it's in the form <key: value>.
The key must be a Hashable
type to ensure that the key is unique.
To better understand the issue, play around with this in an Xcode playground project:
let str: Any = "💩"
testConvert(str)
let dict = ["one": 1, "two": 2]
testConvert(dict)
func testConvert(_ something: Any) {
guard let dict = something as? [AnyHashable: Any] else {
print("\(something) couldn't be converted to Dictionary")
return
}
print("\(something) successfully converted to Dictionary")
}
Prints:
💩 couldn't be converted to Dictionary
["one": 1, "two": 2] successfully converted to Dictionary
mySelf Code
In NetWorkingTool.swift
import UIKit
import Alamofire
class NetWorkingTool: NSObject {
static let shendInstance = NetWorkingTool()
private override init() {}
public func getData(url: String, dataBlock:@escaping (_ resData: Any) ->(), errorBlock:@escaping (_ error: Error) -> ()) -> Void {
Alamofire.request(url).responseJSON { (responseData) in
if let json = responseData.result.value {
dataBlock(json)
}else{
errorBlock(responseData.error!)
}
}
}
}
In ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NetWorkingTool.shendInstance.getData(url: "you url", dataBlock: { (responseData) in
guard responseData is [AnyHashable: Any] else{
print("\(type(of: responseData))")
let dataArray = responseData as! Array<Any>
for dict in dataArray {
let d = dict as! Dictionary<String, AnyObject>
print(d["title"]!)
}
return
}
print("\(type(of: responseData))")
}) { (error) in
print(error)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With