在Swift 3中获取转换NSURLSession到URLSession的错误

时间:2016-11-08 02:21:03

标签: swift swift3 nsurlsession nsurl nsurlsessiondatatask

我尝试在Swift 3上转换下面的代码:

override func calculateAccumulatedFrame() -> CGRect {
    let length = bezierPath.bounds.size.width + initialLineWidth
    let origin = CGPoint(x: bezierPath.bounds.origin.x - 5, y: bezierPath.bounds.origin.y - 5)
    return CGRect(origin: origin, size: CGSize(width: length, height: length))
}

所以我这样做:

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()  

但是有这个错误:

  

对成员'dataTask(with:completionHandler:)'

的模糊引用

为什么会出现此错误?

2 个答案:

答案 0 :(得分:1)

您收到此错误,因为在Swift 3中,他们使用了URL而不是NSURL的所有API,因此只需创建URL而不是NSURL的对象,传递为dataTask(with:completionHandler:)的第一个参数。

let url = URL(string: stringURL)
//Now this will works for you
session.dataTask(with: url!) { (data, response, error) -> Void in

有关此检查URLSession文档的详细信息。

注意:您也可以使用。

dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask

但为此,您需要创建URLRequest对象而不是NSURLRequest

答案 1 :(得分:0)

您只需要在 Swift 3

中进行更改
session.dataTask(with: url!) { (data, response, error) -> Void in

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

Swift 3

中尝试以下URLSession代码
//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
    }