Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug) Ask Question

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug) Ask Question

Hello I have working json parsing code for swift2.2 but when i use it for Swift 3.0 gives me that error

ViewController.swift:132:31: Ambiguous reference to member 'dataTask(with:completionHandler:)'

My code is here:

   let listUrlString =  "http://bla.com?batchSize=" + String(batchSize) + "&fromIndex=" + String(fromIndex)
    let myUrl = URL(string: listUrlString);
    let request = NSMutableURLRequest(url:myUrl!);
    request.httpMethod = "GET";
    
    let task = URLSession.shared().dataTask(with: request) {
        data, response, error in
        
        if error != nil {
            print(error!.localizedDescription)
            DispatchQueue.main.sync(execute: {
                AWLoader.hide()
            })
            
            return
        }
        
        do {
            
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
            
            if let parseJSON = json {
                
                var items = self.categoryList
                
                items.append(contentsOf: parseJSON as! [String])
                
                if self.fromIndex < items.count {
                    
                    self.categoryList = items
                    self.fromIndex = items.count
                    
                    DispatchQueue.main.async(execute: {
                        
                        self.categoriesTableView.reloadData()
                        
                        AWLoader.hide()
                        
                    })
                }else if( self.fromIndex == items.count){
                    
                    
                    DispatchQueue.main.async(execute: {
                        
                        AWLoader.hide()
                        
                    })
                    
                }
                
                
                
            }
            
        } catch {
            AWLoader.hide()
            print(error)
            
        }
    }
    
    task.resume()

Thanks for ideas.

ベストアンサー1

The compiler is confused by the function signature. You can fix it like this:

let task = URLSession.shared.dataTask(with: request as URLRequest) {

But, note that we don't have to cast "request" as URLRequest in this signature if it was declared earlier as URLRequest instead of NSMutableURLRequest:

var request = URLRequest(url:myUrl!)

NSMutableURLRequestこれは、 との間の自動キャストでありURLRequest、失敗しているため、ここでこのキャストを実行する必要があります。

おすすめ記事