如何在Swift中使用Web服务调用启动类?

时间:2015-03-12 15:54:26

标签: ios iphone xcode swift

我有一个药物类,我想通过传递upc来实现:Int。在init内部,我想进行Web服务调用,并使用返回的JSON(NSDictionary)填充类中的值。

我有一个开始,但不是结束。我到处都是错误,似乎无法弄清楚如何最好地实现这一目标。也许我会以错误的方式解决这个问题。有人可以帮忙吗?

这是代码..

init(upc: Int) {
    let apiKey = "xx"
    let baseURL = NSURL(string: "http://something.com/\(apiKey)/")
    let getDrugByUpcURL = NSURL(string: "\(upc).json", relativeToURL: baseURL)

    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    let usernamePasswordString = "user:pass"
    let usernamePasswordData = usernamePasswordString.dataUsingEncoding(NSUTF8StringEncoding)
    let base64EncodedCredential = usernamePasswordData!.base64EncodedStringWithOptions(nil)
    let authString = "Basic \(base64EncodedCredential)"
    config.HTTPAdditionalHeaders = ["Authorization": authString]

    let session = NSURLSession(configuration: config)

    let downloadTask: NSURLSessionDownloadTask = session.downloadTaskWithURL(getDrugByUpcURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
        if (error == nil) {
            let dataObject = NSData(contentsOfURL: location)
            println(dataObject)
            let drugDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
            println(drugDictionary["din"])

            drug_id = drugDictionary["drug_id"] as Int
            din = drugDictionary["din"] as String
            packsize = drugDictionary["packsize"] as Double
            brand = drugDictionary["brand"] as String
            //generic = drugDictionary["generic"] as String
            strength = drugDictionary["strength"] as String
            form = drugDictionary["form"] as String
            upc = drugDictionary["upc"] as String
            //priceGroup = drugDictionary["price_group"] as String
            //manufacturer = drugDictionary["manufacturer"] as String
            onHandQuantity = drugDictionary["onhand"] as Double
            //vendorCost = drugDictionary["vendor_cost"] as Double
            //basePrice = drugDictionary["base_price"] as Double
            //discount = drugDictionary["discount"] as Double
            //price = drugDictionary["price"] as Double
        } else {
            println(error)
        }
    })

    downloadTask.resume()
}

我收到的错误是所有属性分配行:无法分配给' drug_id'在' self'。

1 个答案:

答案 0 :(得分:0)

问题是你是从一个闭包中访问那些实例变量,闭包是downloadTaskWithURL:的完成处理程序。

通过在self.前加上变量,可以很容易地解决这个问题。因此drug_id变为self.drug_id

但是请注意,您在上面的代码中所做的可能是一个坏主意。或者至少是一个非常罕见的设计:我不认为在你的课堂上做异步网络请求是个好主意。初始化程序。

由于对NSURLSessionDownloadTask的调用是异步的,因此init()将立即返回未初始化的数据,然后在某个未指定的时刻,您的类将完全填充来自Web服务调用的结果。你不知道那个时刻是什么时候,所以你真的没有办法知道你的实例什么时候准备就绪。

这很可能不是你想到的。