Swift 3 using AFNetworking
Solution 1
Error is clearly saying that use Error
instead of NSError
, in Swift 3 you need to use Error
instead of NSError
. So change your code like below.
func getJSON() {
let manager = AFHTTPSessionManager()
manager.get(
url,
parameters: nil,
success:
{
(operation, responseObject) in
if let dic = responseObject as? [String: Any], let matches = dic["matches"] as? [[String: Any]] {
print(matches)
}
DispatchQueue.main.async {
self.tollBothPlazaTableView.reloadData()
}
},
failure:
{
(operation, error) in
print("Error: " + error.localizedDescription)
})
}
Note: Always perform UI changes on main thread when you are on background thread, so batter to reload your tableView
on main thread like I have done, Also use Swift native Array
and Dictionary
instead of NSArray
and NSDictionary
.
Solution 2
**Its Better to use Alamofire(same developer) in swift 3 **
func jsonRequest()
{
let url = "url"
//if you want to add paramter
parametr = ["username" : "user" , "password"]
Alamofire.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default)
.responseJSON { response in
// print(response)
//to get status code
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let array = response.result.value as? //NSDictionary [[String : Any]]
{
}
}
}
NotABot
Updated on August 25, 2022Comments
-
NotABot over 1 year
I am using AFNetworking with Swift 3.0 and I am stuck on one code.
func getJSON() { let manager = AFHTTPSessionManager() manager.get( url, parameters: nil, success: { (operation: URLSessionTask!, responseObject: Any?) in print("JSON: " + responseObject!.description) self.matchesArray = responseObject!.object(forKey: "matches")! as? NSMutableArray self.tollBothPlazaTableView.reloadData() }, failure: { (operation: URLSessionTask!, error: NSError) in print("Error: " + error.localizedDescription) } ) }
It shows error on
failure
block.Cannot convert value of type '(URLSessionTask!, NSError) -> ()' to expected argument type '((URLSessionDataTask?, Error) -> Void)?'`
Can someone explain what is wrong in my code. Also the correct way to use closures? (I am new to swift).
-
NotABot over 7 yearsThank you. This solved it. So should I declare my array as Array and not NSMutableArray?
-
seggy over 7 yearsok no problem but try Alamofire is better than Afnetworing :-) Happy Coding
-
Nirav D over 7 years@thewarri0r9 Welcome mate, Declare your array as Array of dictionary like my answer if it contains dictionary like
var matchesArray = [[String:Any]]()
, declare it as String array if it contains String likevar matchesArray = [String]()
-
AlexK over 6 yearsBut if you have a hybrid project, having two frameworks that do the same thing isn't always desired. AlamoFire is better and we use it in our Swift-only/mostly project - but if you have 90% ObjC - its just not practical.