iOS Swift JSON函数调用乱序

时间:2015-06-20 21:46:03

标签: ios json function swift

我是一个相对较新的iOS程序员,我正在开发一个条形码扫描程序,它使用一个函数从使用JSON的URL获取产品的名称。为简单起见,我将所有内容放在一个视图控制器上,因为我希望最终将所有内容都实现到一个视图上但是,我目前仍然坚持这个问题。当我进行函数调用时,函数中的println()似乎在我的viewDidLoad()函数完成后执行。继承我的视图控制器代码:

  "ssh_host_port_min": 3213,
  "ssh_host_port_max": 3214,
  "qemuargs": [
    ["-netdev", "user,id=user.0,hostfwd=tcp::3213-:22,hostfwd=tcp::3214-:22,net=10.0.2.0/24"],
    ["-device", "virtio-net,netdev=user.0"],
    ["-netdev", "user,id=user.1"],
    ["-device", "virtio-net,netdev=user.1"],
    ["-netdev", "user,id=user.2"],
    ["-device", "virtio-net,netdev=user.2"],
    ["-m", "128M"]
  ],

}

代码的输出是:

import UIKit

var productName = ""

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    var sendBarcode = "0068274346613"

    productName = getProductName(sendBarcode)

    println("Product Name2: " + productName)

    }

    func getProductName(barcode: String) -> String{
        // Now escape anything else that isn't URL-friendly

        var prodName = ""
        var barcodeID = barcode

        if let escapedSearchTerm = barcodeID.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
            let urlPath = "https://www.outpan.com/api/get-product.php?barcode=" + escapedSearchTerm + "&apikey=600abe49c13da26c61ae2cb92300b3dc"
        let url = NSURL(string: urlPath)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
            println("Task completed")
            if(error != nil) {
                // If there is an error in the web request, print it to the console
                println(error.localizedDescription)
            }
            var err: NSError?
            if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary {
                if(err != nil) {
                    // If there is an error parsing JSON, print it to the console
                    println("JSON Error \(err!.localizedDescription)")
                }
                if let prodNameRes = jsonResult["name"] as? String {
                    dispatch_async(dispatch_get_main_queue(), {
                        productName = prodNameRes
                        println("Product Name: " + productName)
                    })
                }
            }
        })

        // The task is just an object with all these properties set
        // In order to actually make the web request, we need to "resume"
        task.resume()

    }

    return productName
}

根据我以前的编程知识,我假设"产品名称:..."将首先打印出来,因为我先调用它的功能,然后是"任务完成"因为收到了JSON数据,然后是"产品名称2:..."。

我做错了吗?或者我对代码执行方式的理解不正确?

非常感谢您的帮助。

0 个答案:

没有答案