Search code examples
swiftswift3nsurlsessionnsurlnsurlsessiondatatask

Getting errors for conversion NSURLSession to URLSession in Swift 3


I tried convert the below code on Swift 3:

session.dataTaskWithURL(url! as URL, completionHandler: { (data : NSData?, response : URLResponse?, error : NSError?) -> Void in  

                if error != nil {  
                    callback(items: nil, errorDescription: error!.localizedDescription, placesDetail: [])  
                }  

                if let statusCode = response as? NSHTTPURLResponse {  
                    if statusCode.statusCode != 200 {  
                        callback(items: nil, errorDescription: "Could not continue.  HTTP Status Code was \(statusCode)", placesDetail: [])  
                    }  
                }  

                NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in  
                    callback(items: GooglePlaces.parseFromData(data!), errorDescription: nil, placesDetail: GooglePlaces.arrayPlaces(data!))  
                })  
            }).resume()  

So I do it:

session.dataTask(with: url!) { (data, response, error) -> Void in

                if error != nil {
                    callback(items: nil, errorDescription: error!.localizedDescription, placesDetail: [])
                }

                if let statusCode = response as? NSHTTPURLResponse {
                    if statusCode.statusCode != 200 {
                        callback(items: nil, errorDescription: "Could not continue.  HTTP Status Code was \(statusCode)", placesDetail: [])
                    }
                }

                OperationQueue.main.addOperation {
                    callback(items: GooglePlaces.parseFromData(data!), errorDescription: nil, placesDetail: GooglePlaces.arrayPlaces(data!))
                }
            }

But Have this error:

Ambiguous reference to member 'dataTask(with:completionHandler:)'

Why this error?


Solution

  • You need to change only in Swift 3

    session.dataTask(with: url!) { (data, response, error) -> Void in
    

    to

    session.dataTask(with: url as URLRequest) {
                data, response, error in
    

    Try this below code for URLSession in Swift 3

    //MARK:- Parsing API here
        public static func getparseMyApi(_ input: String, action:String, completion: @escaping (_ result: String, _ error: NSError?) -> Void) {
    
            //Main API here
            let is_URL: String = "http://yourURLhere.com"
    
            let lobj_Request = NSMutableURLRequest(url: URL(string: is_URL)!)
            let session = URLSession.shared
    
            lobj_Request.httpMethod = "POST"
            lobj_Request.httpBody = input.data(using: String.Encoding.utf8)
            //lobj_Request.addValue("www.cgsapi.com", forHTTPHeaderField: "Host")
            lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
            lobj_Request.addValue(String(input.characters.count), forHTTPHeaderField: "Content-Length")
            lobj_Request.addValue("http://tempuri.org/IService/\(action)", forHTTPHeaderField: "SOAPAction")
    
    
            let task = session.dataTask(with: lobj_Request as URLRequest) {
                data, response, error in
                print("Response: \(response)")
    
                // Checking here Response
            if response != nil {
    
                let statusCode = (response as! HTTPURLResponse).statusCode
                print("Success: \(statusCode)")
    
                // Checking here Response Status
            if statusCode == 200 {
                //Handling Data here
                if data?.count > 0 {
                  //Do something here with data
                  let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                    // Finish here Process
                     completion(strData, nil)
                }else{
                    //Data nil Condition here
                    completion("", error as NSError?)
                }
    
                //Handling Error here
                if error != nil
                {
                    print("Error: " + error.debugDescription)
                    completion("", error as NSError?)
                }
    
              }else{
                    //Invalid Status
                    print("Error: " + error.debugDescription)
                    completion("", error as NSError?)
                }
    
             }else{
                //Response Nil then handle here
                print("Error: " + error.debugDescription)
                completion("", error as NSError?)
             }
    
            }
            task.resume()
        }
    
      //MARK:- String To Dictionary Conversion
        public static func convertStringToDictionary(_ json: String) -> [String: AnyObject]? {
            if let data = json.data(using: String.Encoding.utf8) {
                do{
                    let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [String: AnyObject]
                    print(json)
                    return json
                }catch {
                    print(error)
                }
            }
            return nil
        }