Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not cast value of type 'NSMutableURLRequest' (0x11beb7040) to 'Alamofire.URLRequestConvertible' (0x11beb9040)

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)                                
        }
    }
like image 775
Om Bhagwan Avatar asked Dec 13 '16 06:12

Om Bhagwan


2 Answers

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.

like image 145
Nemanja Avatar answered Oct 19 '22 23:10

Nemanja


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)                                
            }
        }
like image 9
raju kumar Avatar answered Oct 19 '22 23:10

raju kumar