Swift 2.0 code for Facebook Friend Invite

2020-07-13 07:26发布

问题:

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.

回答1:

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


回答2:

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


回答3:

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