Swift 2.0 code for Facebook Friend Invite

2020-07-13 07:10发布

I've been looking for an equivalent Swift code sample for Facebook friend invite for iOS apps. But I can't find them.

I understand that there is the Objective-C version on Facebook page https://developers.facebook.com/docs/app-invites/ios. However, because I started off with Swift, I find it difficult to translate.

Could someone point me to a source? Thank you.

3条回答
欢心
2楼-- · 2020-07-13 07:53

the code working :

-In viewDidLoad :

let content = FBSDKAppInviteContent()
content.appLinkURL = NSURL(string: "https://test/myapplink")
content.appInvitePreviewImageURL = NSURL(string: "https://test/myapplink")
// Old Way, now depreciated :
//FBSDKAppInviteDialog.showFromViewController(self, withContent: content, delegate: self)
//New way : 
        FBSDKAppInviteDialog.showFromViewController(self, withContent: content, delegate: self)
// Do any additional setup after loading the view.

-In your viewController to conform the protocol delegate:

extension InviteFriendsViewController: FBSDKAppInviteDialogDelegate{
    func appInviteDialog(appInviteDialog: FBSDKAppInviteDialog!, didCompleteWithResults results: [NSObject : AnyObject]!) {
        //TODO
    }
    func appInviteDialog(appInviteDialog: FBSDKAppInviteDialog!, didFailWithError error: NSError!) {
        //TODO
    }
}
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-07-13 07:54

Facebook Friend invite in Swift 3.0

First of all, import FBSDKCoreKit, FBSDKShareKit and add delegate FBSDKAppInviteDialogDelegate. Then, on invite friend button click, add the code below:

let inviteDialog:FBSDKAppInviteDialog = FBSDKAppInviteDialog()
if(inviteDialog.canShow()){
    let appLinkUrl:NSURL = NSURL(string: "http://yourwebpage.com")!
    let previewImageUrl:NSURL = NSURL(string: "http://yourwebpage.com/preview-image.png")!

    let inviteContent:FBSDKAppInviteContent = FBSDKAppInviteContent()
    inviteContent.appLinkURL = appLinkUrl as URL!
    inviteContent.appInvitePreviewImageURL = previewImageUrl as URL!

    inviteDialog.content = inviteContent
    inviteDialog.delegate = self
    inviteDialog.show()
}

Then, add the methods below of FBSDKAppInviteDialogDelegate:

func appInviteDialog (_ appInviteDialog: FBSDKAppInviteDialog!, didCompleteWithResults results: [AnyHashable : Any]!) {
    let resultObject = NSDictionary(dictionary: results)

    if let didCancel = resultObject.value(forKey: "completionGesture")
    {
        if (didCancel as AnyObject).caseInsensitiveCompare("Cancel") == ComparisonResult.orderedSame
        {
            print("User Canceled invitation dialog")
        } 
    } 
} 
func appInviteDialog(_ appInviteDialog: FBSDKAppInviteDialog!, didFailWithError error: Error!) {
    print("Error tool place in appInviteDialog \(error)")
}
查看更多
神经病院院长
4楼-- · 2020-07-13 08:15

Benobab solution is perfect, i just want to to add that in my case trying to run FBSDKAppInviteDialog.showFromViewController on viewDidAppear worked better.

查看更多
登录 后发表回答