ios swift 分享_iOS Swift Facebook分享

ios swift 分享

Facebook Sharing SDK is a user friendly tools for sharing photos, videos and links easily through your app. User can share the media as a news feed or Story to Facebook app or as a direct message to a friend in Messenger app.

˚Facebook共享SDK是通过你的应用程序共享照片,视频和链接很容易,用户友好的工具。 用户可以将媒体作为新闻源或Story共享给Facebook应用程序,也可以作为直接消息共享给Messenger应用程序中的朋友。

Image for post
Post as a News Feed (Left) & as a Story (Middle) & as a direct message (Right)
作为新闻源(左侧)和作为故事(中间)以及作为直接消息(右侧)发布

The sharing code is short and simple. The following is a set of code for sharing an image as a direct message to a friend through Messenger app. It is only 10 lines long!

共享代码简短而简单。 以下是用于通过Messenger应用程序将图像作为直接消息共享给朋友的一组代码。 它只有10行!

// Same as previous session
let image = UIImage(named: "AppIcon")!
let photo = SharePhoto(image: image, userGenerated: true)
let photoContent = SharePhotoContent()
photoContent.photos = [photo]
photoContent.hashtag = Hashtag("#fooHashTag")


// Show as a message dialog -> Messenger App
let messageDialog = MessageDialog(content: photoContent, delegate: self)
messageDialog.show()

However, there are some limitations on each shared media (file size & maximum number of file) and tricks on providing better UI/UX. They will all be covered in this article.

但是,每种共享媒体都有一些限制(文件大小和最大文件数),以及提供更好的UI / UX的技巧。 它们都将在本文中介绍。

开始之前 (Before start)

  1. Please implement the Facebook Login SDK and login as through Facebook in order to get a valid access token to share through Facebook Sharing SDK.

    请实现Facebook登录SDK并通过Facebook登录,以获取有效访问令牌以通过Facebook Sharing SDK进行共享。

  2. Please run your app in real device instead of simulator since Facebook app and Messenger app cannot be installed in simulator

    由于无法在模拟器中安装Facebook应用程序和Messenger应用,请在真实设备而非模拟器中运行您的应用

添加Facebook ShareKit依赖项 (Add Facebook ShareKit dependency)

Add the following line into Podfile and install dependency by running pod install

Podfile添加到Podfile并通过运行pod install安装依赖项

pod ‘FBSDKShareKit’

分享内容 (Sharing content)

Image for post

There are 3 types of media that can be shared through Facebook and each of them has different limitations:

可以通过Facebook共享三种类型的媒体,每种媒体都有不同的限制:

照片 (Photo)

  1. Each individual image must be smaller than 12MB

    每个单独的图像必须小于12MB

视频 (Video)

  1. Each individual video must be smaller than 50MB

    每个单独的视频必须小于50MB

带视频的照片 (Photo with Video)

  1. User can only upload 1 video with 29 photos or 30 photos each time at most. In other words, the total uploaded media files cannot be larger than 30.

    用户最多只能上传1张包含29张照片或30张照片的视频。 换句话说,上传的媒体文件总数不能大于30。

分享频道 (Sharing channel)

Image for post

Facebook SDK provides two ways to share media through Facebook:

Facebook SDK提供了两种通过Facebook共享媒体的方式:

  1. ShareDialog — Media is shared to user’s news feed or story.

    ShareDialog —媒体已共享到用户的新闻提要或故事。

    * Multimedia files (e.g. more than 1 photo) can only be shared to news feed.

    *多媒体文件(例如,一张以上的照片)只能共享到新闻源。

  2. MessageDialog — Media is sent to a user’s friend directly in private channel

    MessageDialog-媒体直接通过私人频道发送给用户的朋友

准备共享资料 (Preparation of Sharing materials)

Please refer to the below Medium post for selecting image and video from user’s device or camera source:

请从下面的中篇文章中选择从用户设备或相机来源选择图像和视频:

照片 (Photo)

func getPhotoSharingContent() -> SharingContent {
  // Create `SharePhoto` object
  let image = UIImage(named: "AppIcon")!
  let photo = SharePhoto(image: image, userGenerated: true)
  
  // Add data to `SharePhotoContent`
  let photoContent = SharePhotoContent()
  photoContent.photos = [photo]
  
  // Optional:
  photoContent.hashtag = Hashtag("#fooHashTag")
  
  return content
}
Image for post

For all shared photos, it has to be wrapped by a SharePhoto object which is embedded into SharePhotoContent. The SharePhotoContent will then be used in ShareDialog and MessageDialog in next session.

对于所有共享照片,必须由嵌入到SharePhotoContentSharePhoto对象SharePhotoContent 。 该SharePhotoContent将被用于ShareDialogMessageDialog在下次会议。

视频 (Video)

/* 
   `videoAsset` is retrieved from the `info` of the 
   `imagePickerController(_:didFinishPickingMediaWithInfo:)` of `UIImagePickerViewControllerDelegate`
    
   Make sure the `NSPhotoLibraryUsageDescription` is added to the info.plist

   ```
   let selectedPHAsset = info[UIImagePickerController.InfoKey.phAsset] as! PHAsset
   ```
*/
func getVideoSharingContent(videoAsset: PHAsset) -> SharingContent {
  // Construct a `SharedVideo`
  let video = ShareVideo()
  video.videoAsset = videoAsset


  // Embed `SharedVideo` to `ShareVideoContent`
  let videoContent = ShareVideoContent()
  videoContent.video = video


  // Optional:
  videoContent.hashtag = Hashtag("#fooHashTag")
  
  return videoContent
}

Similar to the way of sharing photo, video data is wrapped by a ShareVideo which is embedded into ShareVideoContent.

类似的共享照片的方式,视频数据是由一缠绕ShareVideo被嵌入ShareVideoContent

链接 (Link)

func getLinkSharingContent() -> SharingContent {
  let shareLinkContent = ShareLinkContent()
  shareLinkContent.contentURL = URL(string: "https://apps.apple.com/us/app/facebook/id284882215")!
  
  // Optional:
  shareLinkContent.hashtag = Hashtag("#fooHashTag")
  shareLinkContent.quote = "fooQoute"
  
  return shareLinkContent
}
Image for post

Link is the easiest one and developer just needs to define the url.

链接是最简单的链接,开发人员只需定义URL。

通过ShareDialog分享 (Sharing through ShareDialog)

Image for post
// Same as previous session
let image = UIImage(named: "AppIcon")!
let photo = SharePhoto(image: image, userGenerated: true)
let photoContent = SharePhotoContent()
photoContent.photos = [photo]
photoContent.hashtag = Hashtag("#fooHashTag")


// Share the content (photo) as a dialog with News Feed / Story
let sharingDialog = ShareDialog.init(fromViewController: self, content: photoContent, delegate: self)
sharingDialog.show()

At line 10, a ShareDialog is created with the UIViewController instance , which is going to present the dialog, and the photoContent that is defined in the previous session. At line 11, it can then be simply presented by calling show() function. The delegate ShareDelegate will be discussed in later session.

在第10行,使用UIViewController实例创建一个ShareDialog ,该实例将显示该对话框以及在上一个会话中定义的photoContent 。 然后,在第11行,可以通过调用show()函数来简单地呈现它。 委托ShareDelegate将在以后的会议中进行讨论。

通过Messenger分享 (Sharing through Messenger)

Image for post
// Same as previous session
let image = UIImage(named: "AppIcon")!
let photo = SharePhoto(image: image, userGenerated: true)
let photoContent = SharePhotoContent()
photoContent.photos = [photo]
photoContent.hashtag = Hashtag("#fooHashTag")


// Show as a message dialog -> Messenger App
let messageDialog = MessageDialog(content: photoContent, delegate: self)
messageDialog.show()

Unlike ShareDialog, MessageDialog is shown by launching and delegating to Messaging app directly. Therefore, there is no need for a UIViewController instance in its constructor. The function for showing a MessageDialog is the same as the one for ShareDialog, i.e. show().

ShareDialog不同, MessageDialog是通过直接启动并委托给Messaging应用程序来显示的。 因此,在其构造函数中不需要UIViewController实例。 用于显示MessageDialog的函数与用于ShareDialog的函数相同,即show()

共享代表 (SharingDelegate)

extension FooFacebookViewController: SharingDelegate {
  func sharer(_ sharer: Sharing, didCompleteWithResults results: [String : Any]) {
    printLog("didCompleteWithResults")
  }


  func sharer(_ sharer: Sharing, didFailWithError error: Error) {
    printLog("didFailWithError: \(error.localizedDescription)")
  }


  func sharerDidCancel(_ sharer: Sharing) {
    printLog("sharerDidCancel")
  }
}

Facebook SDK provides 3 callbacks on sharing through Facebook.

Facebook SDK提供了3个通过Facebook共享的回调。

didCompleteWithResults is triggered when user has just successfully shared through Facebook SDK.

当用户刚刚通过Facebook SDK成功共享时,将触发didCompleteWithResults

didFailWithError is triggered when there is an error during the sharing. For example, com.facebook.sdk.share error 2 represent a connection timeout.

共享期间发生错误时,将触发didFailWithError 。 例如, com.facebook.sdk.share error 2表示连接超时。

sharerDidCancel is triggered when user cancels his / her sharing.

当用户取消他/她的共享时,将触发sharerDidCancel

检查是否安装了Facebook和Messenger (Check if Facebook & Messenger installed)

func checkIfFacebookAppInstalled() -> Bool {
    let facebookAppUrl = URL(string: "fb://")!
    return UIApplication.shared.canOpenURL(facebookAppUrl)
  }
  
  func checkIfFacebookMessengerAppInstalled() -> Bool {
    let facebookMessengerAppUrl = URL(string: "fb-messenger://")!
    return UIApplication.shared.canOpenURL(facebookMessengerAppUrl)
  }

In order to provide a better UI/ UX, it is necessary to hide the “Share to Facebook” button and optionally redirect user to App Store, when Facebook or Messenger app is not installed. The above codes provide a simple to use function to check the existence of the two apps.

为了提供更好的UI / UX,当未安装Facebook或Messenger应用程序时,有必要隐藏“ Share to Facebook”按钮并有选择地将用户重定向到App Store。 上面的代码提供了一个易于使用的功能来检查两个应用程序的存在。

Image for post
LSApplicationQueriesSchemes at info.plist
LSApplicationQueriesSchemes位于info.plist

Make sure that the LSApplicationQueriesSchemes in info.plist must include the fb & fb-messenger in order to check the app existences.

确保info.plist中的LSApplicationQueriesSchemes必须包含fbfb-messenger以便检查应用程序是否存在。

摘要 (Summary)

  1. Facebook provides an easy to use SDK for sharing media through Facebook.

    Facebook提供了一个易于使用的SDK,用于通过Facebook共享媒体。
  2. User can share links, photos and videos through the SDK in form of news feed, story and direct message.

    用户可以通过SDK以新闻摘要,故事和直接消息的形式共享链接,照片和视频。
  3. Photos cannot be larger than 12MB and videos cannot be larger than 50MB.

    照片不能大于12MB,视频不能大于50MB。
  4. The maximum number of photo with video in a batch is 30.

    一批中最多可以有30张带视频的照片。
  5. HashTag can be optionally added to each kind of sharing content.

    HashTag可以选择添加到每种共享内容中。
  6. SharingDelegate provides callbacks for monitoring the sharing process.

    SharingDelegate提供了用于监视共享过程的回调。

  7. To provide a better UI/UX, please hide the sharing widgets when Facebook or Messenger is not installed.

    为了提供更好的UI / UX,请在未安装Facebook或Messenger时隐藏共享窗口小部件。

您可能想要 (You probably would like)

进一步的阅读和参考 (Further readings & Reference)

  1. Facebook Developer website about sharing

    Facebook开发者网站有关共享的信息

2. StackOverflow — About how to check the existence of a certain app

2. StackOverflow —关于如何检查某个应用程序是否存在

Image for post

You are welcome to follow me at Twitter@myrick_chow for more information and articles. Thank you for reading this article. Have a nice day! 😄

欢迎您通过Twitter @ myrick_chow关注我,以获取更多信息和文章。 感谢您阅读本文。 祝你今天愉快! 😄

翻译自: https://itnext.io/ios-swift-facebook-sharing-e473e6b2fc48

ios swift 分享

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值