来自Swift 2类型的抛出函数的转换无效

时间:2015-09-18 02:57:42

标签: swift

我将我的应用迁移到Swift 2并收到错误

  

来自

类型的投掷功能的转换无效

在以下一行:

NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue(), completionHandler: {

这是完整的代码块:

 NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue(), completionHandler: {
    response, data, error in

    let image = UIImage(data: data!)

    self.profilePic.image = image

    if var realUser = user {

        realUser["image"] = data as! AnyObject

        try realUser.save()

        FBRequestConnection.startForMeWithCompletionHandler({
            connection, result, error in

            realUser["first_name"] = result["first_name"]
            realUser["last_name"] = result["last_name"]

            try realUser.save()  
        })
    }
})

如何使用Swift 2中实现的新catch来修复此代码?

谢谢!

2 个答案:

答案 0 :(得分:2)

传递给sendAsynchronousRequest的块不允许抛出错误。所以你必须抓住错误:

do {
    try realUser.save()
}
catch {
    // handle the error
}

答案 1 :(得分:0)

试试这段代码:

NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue(), completionHandler: {
response, data in

let image = UIImage(data: data!)

self.profilePic.image = image

if var realUser = user {

    realUser["image"] = data as! AnyObject

    do {
        try realUser.save()
    }
    catch {
        print(error)
    }
    FBRequestConnection.startForMeWithCompletionHandler({
        connection, result, error in

        realUser["first_name"] = result["first_name"]
        realUser["last_name"] = result["last_name"]

    do {
        try realUser.save()
    }
    catch {
        print(error)
    }
    })
}
})