Swift POST请求和活动指示器

时间:2018-01-24 16:37:49

标签: ios swift nsurl uiactivityindicatorview swifty-json

您好我正在使用SwiftyJSON库从服务器获取数据。我的代码如下:

    let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
    let message2  = "Please wait..."
    var messageMutableString = NSMutableAttributedString()
    messageMutableString = NSMutableAttributedString(string: message2 as String, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue-Bold",size: 15.0)!])
    alert.setValue(messageMutableString, forKey: "attributedMessage")
    let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
    loadingIndicator.hidesWhenStopped = true
    loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
    loadingIndicator.startAnimating();



    alert.view.addSubview(loadingIndicator)
    present(alert, animated: true, completion: nil)

    var request = URLRequest(url: URL(string: Global.ipAdres)!)
        request.httpMethod = "POST"
        let postString = Global.postString
        request.httpBody = postString.data(using: .utf8)


    let task = URLSession.shared.dataTask(with: request)
    {                                                   data, response, error in


        DispatchQueue.main.async {
            self.printNameSurname()
            self.dismiss(animated: true, completion: nil)
        }
        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return;
        }
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200
        {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }            
        let json = JSON(data)

        GlobalVariable.nameSurname = json["data"]["nameSurname"].stringValue + json["data"]["sad"].stringValue
        GlobalVariable.id = json["data"]["id"].stringValue
        GlobalVariable.id2 = json["data"]["id2"].stringValue

    }
    task.resume()

如果我不明白错误,我的printNameSurname()函数需要执行并填充我的视图控制器中的两个标签,当我得到值时,我的活动指示器应该被解除,这就是我把它放在Dispatch.main.async中的原因。但是,它们无法正常工作。我的标签没有填写我提取的数据。我认为问题是关于发布请求,但我搜索了它的例子,但它们不适合我,或者我做错了什么我能解决它?

1 个答案:

答案 0 :(得分:0)

  

在获得响应后,将所有代码放入主队列中。

    let task = URLSession.shared.dataTask(with: request)
    {                                                   data, response, error in

        //Trick here...
        DispatchQueue.main.async {

            self.printNameSurname()
            self.dismiss(animated: true, completion: nil)
            guard let data = data, error == nil else {
                print("error=\(String(describing: error))")
                return;
            }
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200
            {
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }
            let json = JSON(data)

            GlobalVariable.nameSurname = json["data"]["nameSurname"].stringValue + json["data"]["sad"].stringValue
            GlobalVariable.id = json["data"]["id"].stringValue
            GlobalVariable.id2 = json["data"]["id2"].stringValue
        }

    }