如何检索Microsoft Band 1

时间:2015-12-22 07:10:20

标签: ios swift microsoft-band

我使用 Swift iOS 创建 Microsoft Band 1 应用程序 文档中的这个功能让我眼花缭乱。请帮忙。

我知道函数可以作为 Swift 中的类型 即。

var exampleFunction: (String, Int) -> String

是一个函数,它接受两个参数,一个字符串和一个int,并返回一个字符串。

我正在查看的方法在 Xcode (Swift语言)中说明以下内容:

tilesWithCompletionHandler(completionHandler: (([AnyObject]!, NSError!) -> Void)!

我相信,titlesWithCompletionHandler接受一个参数,它是[AnyObject]!, NSError!) -> Void类型的函数我不确定围绕整个事情的()!虽然我知道这迫使一个值超出了可选的......也很难理解。

<{3}}网站上的

它是用 Objective-c 编写的,它将其显示为方法定义:

[self.client.tileManager tilesWithCompletionHandler:^(NSArray *tiles, NSError *error) {
   if (error){
     // handle error
}}];

我所尝试的是构建一个这个要求的类型的函数:

//I had to create this function to match the parameter that the tilesWithCompletionHandler method required
func errorFunction(tileArray: [AnyObject]!, error: NSError!) -> Void {
    print("hello")
    if((error) != nil) {
        //handle error
        print("error was not nil, meaning an error occurred... :(")
    }
    else {
        print("i got here")
        self.tileArray = tileArray
    }
}

然后我创建了一个类型并将其分配给这个函数就像这样(修复了错误 Xcode 当我调用我试图使用的方法时所掌握的错误):

let customFunction: (([AnyObject]!, NSError!) -> Void)! = errorFunction

该类型周围的()!部分仍然让我感到困惑

最后我调用了我需要调用的函数来获取tile并传入我刚刚构造的函数

myBand.tileManager.tilesWithCompletionHandler( customFunction )

编辑:错误与问题无关。打印语句现在打印,但我进入了错误流程。

我能以正确的方式解决这个问题吗?

另外,我试图弄清楚如何处理参数的错误部分。我需要使用

吗?
do {
    try //some code I need to figure out what to write
} catch let error as NSError {
    //code to handle error
}

这个方法中有很多事情要求我完全掌握。任何帮助将非常感激。谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

您的错误处理似乎在errorFunction中是正确的。只需修改print语句,也可以打印错误对象,看看实际错误是什么。

print("error was not nil, meaning an error occurred... :( \(error)")

您可以进一步查看error.code并在您的应用中添加逻辑来处理它。 MSBErrorTypes.h有一个可能的错误代码列表,很可能你的代码将在300范围内。

答案 1 :(得分:0)

在Larme的评论之后,我能够使用Swift中的闭包。 我很好奇我在问题中使用的方法是否有用......

这是我在更新我建议的print语句后所做的,让我知道你也可以这样打印错误! :

    myBand.tileManager.tilesWithCompletionHandler( {(tiles:[AnyObject]!, error: NSError!) -> Void in
        if((error) != nil) {
            //handle error
            print("Error in .tilesWithCompletionHandler: \(error)")
        }
    })

它只是一个闭包,显然相当于Objective-c中的一个块,我之前并不知道它(块部分)。

感谢大家的帮助!