when build my code then crash on Alamofire.request(request as! URLRequestConvertible).responseJSON()
. pls suggest how to fix this crash
let url = NSURL(string: "https://jsonplaceholder.typicode.com/users")
let request = NSMutableURLRequest(url:url! as URL)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(request as! URLRequestConvertible).responseJSON(){ response in
switch response.result
{
case .success(let data):
print(" i got my Data Yup",data)
case .failure(let error):
print(error)
}
}
In Swift 3, all you have to do is to change NSMutableURLRequest to URLRequest and it will work. No need to cast. Also, set var so it can be swift mutable. :) Thanks, Markus for comment.
change let request = NSMutableURLRequest(url:url! as URL)
to
var request = URLRequest(url: NSURL(string: url)! as URL)
your code look like this:-
let url = NSURL(string: "https://jsonplaceholder.typicode.com/users")
var request = URLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(request as! URLRequestConvertible).responseJSON(){ response in
switch response.result
{
case .success(let data):
print(" i got my Data Yup",data)
case .failure(let error):
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