Conversion from the project's Alamofire to swift 3.0

6

I have the following code when I want to make a call to the server:

let mutableURLRequest = NSMutableURLRequest(url: URL)
            mutableURLRequest.httpMethod = "POST"

let parameters = ["SessionID": sessionID]
do {
     mutableURLRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions())
   } catch {}

mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

Alamofire.request(**mutableURLRequest**).responseJSON{

response in if let JSON = response.result.value{}}

Where text is BOLD is giving me error in this variable

Argument type 'NSMutableURLRequest' does not conform to expected type 'URLRequestConvertible'

however give me the following option

Fix-it Insert as! URLRequestConvertible

If I accept the suggestion it is put into the code what they say but the error persists and says to insert again and it is infinitely.

Does anyone know how to solve this problem?

    
asked by anonymous 10.10.2016 / 18:48

2 answers

1

Not being a direct answer to the question, and to get some code here, I just wanted to point out an alternative to using Alamofire just to make HTTP requests. The Alamofire is a cannon and I suggest to use it only when needed. That said, I leave here a code that can be pasted directly into a playground (Xcode 8) and makes a GET to a Stack overflow api endpoint.

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow")!
var request = URLRequest(url: url)
let session = URLSession(configuration: URLSessionConfiguration.default)

session.dataTask(with: request) { (data, response, error) in
    print("response:", response)
    print("error: ", error)

    var responseDictionary: NSDictionary?
    if data != nil {
        do {
            responseDictionary = try JSONSerialization.jsonObject(with: data!,
                                                 options: []) as? NSDictionary
            print(responseDictionary)
        } catch {
            print("error")
        }
    }


    }.resume()
    
12.10.2016 / 13:20
2

Swift 3 you should use URLRequest instead of NSURLRequest. When it is NSMutableURLRequest you should also use URLRequest but as URLRequest is a structure and not a class to be able to change its properties you need to declare your object as variable instead of constant. Also you are passing URL where it should be a URL object:

var mutableURLRequest = URLRequest(url: URL(string: "http://www.exemplo.com")!)
    
11.10.2016 / 07:41