Get progress from Facebook SDK GraphRequest with swift

元气小坏坏 提交于 2019-12-12 22:19:47

问题


I upload an image with this pice of code:

    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")
        }

    })

It works fine so far, but the upload can take a while and I want to inform the user about the current progress. Is there any way to get the current progress? As I can see in the SDK docs, there is a FBSDKGraphRequestConnection that provides a FBSDKGraphRequestConnectionDelegate with progress stuff in requestConnection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:but I´m unable understand, how to implement this stuff in my little pice of code. Can anybody help?


回答1:


I someone else has the same problem ... Google does´t find anything written in swift. Here´s my working solution:

1) Derive your class from NSObject and FBSDKGraphRequestConnectionDelegate

2) Write your upload process like this:

    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) Implement the delegate in your class like this:

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
}


来源:https://stackoverflow.com/questions/38482699/get-progress-from-facebook-sdk-graphrequest-with-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!