Zaid Pathan
Zaid Pathan

Reputation: 16820

Getting WebService response from Block to WatchKit App

I'm currently working on making one app compatible with AppleWatch,

For that I'm calling one WebService, the problem is I'm getting WebService response in Block, and reply() block is not getting called there showing error.

Error,

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

My 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 is our WebService framework.

Upvotes: 0

Views: 290

Answers (2)

Zaid Pathan
Zaid Pathan

Reputation: 16820

So finally I got my answer by doing Sync WS request,

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
}

Upvotes: 0

John
John

Reputation: 8548

The problem is that the method handleWatchKitExtensionRequest is not finishing before the OS kills it. Therefore:

  • Explicitly create a background task.
  • If you want to fetch data asynchroneously, ensure that the method handleWatchKitExtensionRequest is not left before the background fetch has been finished.

Here is a code example that shows how to implement the above.

Upvotes: 1

Related Questions