使用swift从Facebook SDK GraphRequest获得进展

时间:2016-07-20 13:29:00

标签: ios swift facebook facebook-graph-api facebook-ios-sdk

我使用这段代码上传图片:

    FBSDKGraphRequest(graphPath: "me/photos", parameters: params as [NSObject : AnyObject], HTTPMethod: "POST").startWithCompletionHandler({ (connection, result, error) -> Void in

        if (error != nil) {
            print ("failed")
        }
        else {
            print ("success")
        }

    })

到目前为止工作正常,但上传可能需要一段时间,我想告知用户当前的进度。有没有办法获得当前的进展?正如我在SDK文档中看到的那样,有一个FBSDKGraphRequestConnectionFBSDKGraphRequestConnectionDelegate中提供requestConnection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:进度内容但我无法理解,如何在我的小pice中实现这些内容代码有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我有其他人有同样的问题...谷歌找不到任何用swift写的东西。这是我的工作解决方案:

1)从NSObjectFBSDKGraphRequestConnectionDelegate

中获取您的课程

2)写下你的上传过程:

    let uploadRequest = FBSDKGraphRequest(graphPath: "me/photos", parameters: params as [NSObject : AnyObject], HTTPMethod: "POST")
    let connection = FBSDKGraphRequestConnection()
    connection.delegate = self
    connection.addRequest(uploadRequest, completionHandler: {
        (connection, result, error) -> Void in

        if (error != nil) {
            // error handling
        }
        else {
            // success handling
        }
    })
    connection.start()

3)在你的班级中实现这样的委托:

func requestConnection(connection:FBSDKGraphRequestConnection, didSendBodyData bytesWritten:NSInteger, totalBytesWritten:NSInteger, totalBytesExpectedToWrite:NSInteger) {
    print("upload percent reached: " + String(Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)))

    // handle your UI here to show the current status
}