【问题标题】:Ambiguous reference to member 'dataTask(with:completionHandler:)' connect to server对成员 'dataTask(with:completionHandler:)' 的模糊引用连接到服务器
【发布时间】:2023-03-25 16:30:01
【问题描述】:

我正在尝试连接到服务器

如果你有解决办法,请帮我写下来

我如何知道新版本的 swift 有哪些变化?

swift 2 和 swift 3 之间存在很多差异

swift 4 和 swift 3 有很大不同吗?

在 swift 3 中我收到此错误:

let task = URLSession.shared.dataTask(with: server.execute())
{Data,URLResponse,error in
    if error != nil{
    print(error as Any)
        return
    }
    do{
        let json = try JSONSerialization.jsonObject(with: Data!, options: .allowFragments)
        if let json_result = json as? [String: Any]
        {
            let result = json_result ["result"] as? String
            if result == "0"
            {
                DispatchQueue.main.async {
                    let alert = UIAlertController(title:"Incorrect Username",message : "The username you entered doesn't appear to belong to an account. Please check your username and try again", preferredStyle : .alert)
                    let alert_action = UIAlertAction(title: "Try Again", style: .default, handler: nil)
                    alert.addAction(alert_action)
                    self.present(alert, animated: true, completion: nil)
                }
            }
            else
            {
                DispatchQueue.main.async {
                    UserDefaults.standard.set(result!, forKey: "user_id")
                    //" use of unresolved identifier 'result' "
                    let current_view=UIApplication.shared.windows[0] as UIWindow
                    let new_view=(self.storyboard? .instantiateViewController(withIdentifier: "tab_bar"))! as UIViewController
                    UIView.transition(from: (current_view.rootViewController? .view)!, to:new_view.view , duration: 0.65, options: .transitionFlipFromRight, completion: {(action) in current_view.rootViewController=new_view
                    })
                }

            }
        }
        else{
            // Error in jsonSerialization
        }   }
    catch{
    }
}
task.resume()

【问题讨论】:

    标签: ios json swift3 nsurlsession


    【解决方案1】:

    问题几乎可以肯定是server.execute() 的返回值。也许是NSURLNSURLRequest 而不是URLURLRequest。也许这是一个可选的。也许这是完全不同的东西。最重要的是,如果dataTask 的参数不是非可选的URLURLRequest,你会得到你所做的错误。没有看到 execute 返回什么,我们只是在猜测,但这可能是罪魁祸首。


    一些不相关的观察:

    1. 我不会使用DataURLResponse 作为dataTask 闭包的参数名称。这些是数据类型的名称。我会使用dataresponse(或者甚至不指定response,因为你没有使用它),以避免混淆(对于你和编译器)。

    2. 你有很多无关的强制转换,只会给代码增加噪音。例如。 windowsUIWindow 的数组,所以当您从该数组中获取第一项时,为什么还要打扰 as UIWindow

    3. 您有几个可选的链接序列,您稍后会强制解包。这样做没有意义。消除该过程中的可选链接。因此,而不是 storyboard? 后跟 !

      let new_view = (self.storyboard?.instantiateViewController(withIdentifier: "tab_bar"))! as UIViewController
      

      你可以使用storyboard!:

      let controller = self.storyboard!.instantiateViewController(withIdentifier: "tab_bar")
      
    4. 您有几个无关的选项,您可以根据需要删除它们。例如。 .allowFragments for JSONSerialization 是不必要的(并且可能是不可取的)。或者你的UIAlertActionpresentcompletionnil 也是不必要的。没什么大不了的,但它只会给你的代码增加噪音。

    5. 按照惯例,我们不使用_ 字符来分隔变量名中的单词。我们使用camelCase。因此,例如,我们将使用currentView,而不是current_view。 (或者,因为那是一个窗口,我实际上会使用window,这更简单。)

    6. 如果您没有在 catch 块中执行任何操作,则使用 do-try-catch 模式毫无意义。如果您在捕获它时不打算做任何事情,为什么要抛出错误。如果您只关心它是否成功,请使用try?

    因此,代码可以稍微清理一下:

    let task = URLSession.shared.dataTask(with: request) { data, _, error in
        if let error = error {
            print(error)
            return
        }
    
        guard let data = data,
            let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
            let result = json["result"] as? String else {
                print("no result")
                return
        }
    
        DispatchQueue.main.async {
            if result == "0" {
                let alert = UIAlertController(title: "Incorrect Username", message: "The username you entered doesn't appear to belong to an account. Please check your username and try again", preferredStyle: .alert)
                let action = UIAlertAction(title: "Try Again", style: .default)
                alert.addAction(action)
                self.present(alert, animated: true)
            } else {
                UserDefaults.standard.set(result, forKey: "user_id")
                let window = UIApplication.shared.windows[0]
                let controller = self.storyboard!.instantiateViewController(withIdentifier: "tab_bar")
                UIView.transition(from: window.rootViewController!.view, to: controller.view, duration: 0.65, options: .transitionFlipFromRight, completion: { _ in
                    window.rootViewController = controller
                })
            }
        }
    }
    task.resume()
    

    现在,我已将 server.execute() 替换为 request,因为我不知道 execute 在做什么,但请使用合适的(请参阅此答案的开头)。

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 2016-10-15
      • 2019-11-17
      • 1970-01-01
      • 2018-04-02
      • 2018-07-24
      • 2016-11-21
      • 1970-01-01
      相关资源
      最近更新 更多