Reputation: 526
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).
Upvotes: 3
Views: 17981
Reputation: 72410
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
.
Upvotes: 10
Reputation: 1196
**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]]
{
}
}
}
Upvotes: 4