“ let task = session.dataTask(with:urlRequest)”如何工作并返回值?

时间:2018-07-19 12:29:55

标签: ios swift4

最后一个问题是,我很高兴得到了我的帮助,我正在尝试获取这段代码来为我返回一个值,以便可以将其插入情节提要中的文本字段。该代码正在运行-但我不知道如何返回所需的值。 myBalance或btn_balance。

我尝试了“返回值”,但是它忽略了它。 这是我修改的代码。这将在文本字段中打印“ Hello”,但不打印值。我对此有点不满意,恐怕我已经跳入了深渊。我可以像在正常会话中一样从函数返回数据,但是这个“任务”使我不堪重负。

class GetBalanceViewController: UIViewController {

var myBalance :String = ""
var btn_balance :String = ""

@IBOutlet weak var displayBalance: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    //makeGetCall()

    //display the balance on the screen
   // print(makeGetCall(myBalance: btn_balance))
    myBalance =  (makeGetCall(myBalance: btn_balance))
    print("Hello...: \(myBalance)") // blank
    displayBalance.text = (makeGetCall(myBalance: btn_balance)) + "Hello" // displays "Hello" 


    // Do any additional setup after loading the view.

}

功能-经过我的修改,就是这个。

    func makeGetCall(myBalance: String) -> String  {
    // Set up the URL request
    let todoEndpoint: String = "https://api.jsecoin.com/v1.7/balance/auth/0/"
    //let todoEndpoint: String = "https://api.jsecoin.com/v1.7/ledger/auth/"
    //let todoEndpoint: String = "https://api.jsecoin.com/v1.7/balance/checkuserid/73276/auth/"
    let apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"


    guard let url = URL(string: todoEndpoint) else {
        print("Error: cannot create URL")
        return "Error"
    }
    var urlRequest = URLRequest(url: url)

    urlRequest.setValue(apiKey, forHTTPHeaderField: "Authorization")
    urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    // set up the session
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    // make the request
    let task = session.dataTask(with: urlRequest) {
        (data, response, error) in
        // check for any errors
        guard error == nil else {
            print("error calling GET on /todos/1")
            print(error!)
            return
        }


        // make sure we got data
        guard let responseData = data else {
            print("Error: did not receive data")
            return
        }
        print("Got data")
        // parse the result as JSON, since that's what the API provides
        do {
            guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
                as? [String: Any] else {
                    print("error trying to convert data to JSON")
                    return
            }
            // now we have the todo
            // let's just print it to prove we can access it
            print("The todo is: " + todo.description)

            // the todo object is a dictionary
            // so we just access the title using the "title" key
            // so check for a title and print it if we have one
            let index = todo.index(forKey: "notification")

            let btn_balance = (todo[index!].value)

            let myBalance = btn_balance
            print("myBalance I: \(myBalance)")
            print("btn_balance I: \(btn_balance)")

          /*
            for (key,value) in todo
            {
                print("\(key) : \(value)")

            }
           */
        /*
            guard let todoTitle = todo["balance"] as? String
                else {
              //  print("Could not get todo title from JSON")
                return
                }
         */
           //print("The title is: " + todoTitle)
            } catch  {
            print("error trying to convert data to JSON")
            return
        }

    }
   task.resume()
     return btn_balance
}

原始就是这个。

makeGetCall()

func makeGetCall() {
.....
   }
   task.resume()

}

程序在控制台中显示数据,确定

The todo is: ["notification": Your balance is 5646.65 JSE, "balance": 5646.65, "success": 1]
myBalance I: Your balance is 5646.65 JSE
btn_balance I: Your balance is 5646.65 JSE

这就是问题,我如何才能将获得的价值(如您所见)返回到故事板。

1 个答案:

答案 0 :(得分:1)

由于dataTask是异步工作的,因此不能简单地从makeGetCall返回值。相反,您必须在闭包内部更新数据模型或UI。

您可以使makeGetCall返回Void,并在完成处理程序中添加一个DispatchQueue.main.async调用,以更新UI(也许还可以更新属性)。

类似的东西:

func makeGetCall(myBalance: String) -> ()  {
    // ...

    let task = session.dataTask(with: urlRequest) {
        (data, response, error) in

        // ..

        do {
            // ...

            DispatchQueue.main.async {
                if let balanceString = todo[index!].value as? String {    
                    self.btn_balance = balanceString
                    self.displayBalance.text = balanceString
                } else {
                    // Ooops
                    self.displayBalance.text = "?? unknown ??"
                }
            }
            // ...
        }

    }
   task.resume()
}

顺便说一句:为什么要使用局部变量btn_balancemyBalance?我猜你的意思是selft.btn_balanceself.myBalance。如果是这样,您还应该只在DispatchQueue.main.async闭包内写入这些值。