获取从Block到WatchKit App的WebService响应

时间:2015-05-19 09:56:05

标签: ios web-services swift watchkit

我目前正致力于使一个应用与AppleWatch兼容,

为此,我正在调用一个WebService,问题是我在Block中收到WebService响应,并且 reply()块没有被调用,显示错误。

错误,

The UIApplicationDelegate in the iPhone App never called reply() in -[UIApplicationDelegate application:handleWatchKitExtensionRequest:reply:]

我的Appdelegate,

func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) {

    getInfo(userInfo, reply: reply)

}

func getInfo(userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) ->Void)!){

    let dicParam:NSDictionary = [:]

    let wsfr:WSFrameWork = WSFrameWork(URLAndParams:WS_GET_DATA, dicParams: dicParam as [NSObject : AnyObject])

    wsfr.isLogging = false

    wsfr.onError = { (error : NSError!) -> Void in
        reply(nil)
    }

    wsfr.onSuccess = { (dicResponse : Dictionary!) -> Void in

        if dicResponse["data"] != nil{

            let returnData = ["Returned NSData":dicResponse]
            reply(returnData)

        }

    }
}

WSFrameWork是我们的WebService框架。

2 个答案:

答案 0 :(得分:1)

问题是方法handleWatchKitExtensionRequest在操作系统杀死之前没有完成。因此:

  • 明确创建后台任务。
  • 如果您想要异步获取数据,请确保在后台提取完成之前不会留下方法handleWatchKitExtensionRequest

这是一个code example,展示了如何实现上述功能。

答案 1 :(得分:0)

所以最后我通过执行Sync WS请求得到了答案,

func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) {

    getCurrentDataInfo(userInfo, reply: reply)

}

func getCurrentDataInfo(userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) ->Void)!){

    var data = parseJSON(getJSON("https://My_JSON_URL"))

    println(data)

    reply(["myData":data])

}

func getJSON(urlToRequest: String) -> NSData{
    return NSData(contentsOfURL: NSURL(string: urlToRequest)!)!
}

func parseJSON(inputData: NSData) -> NSDictionary{
    var error: NSError?
    var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary

    return boardsDictionary
}