MySocialApp 1.1.2

MySocialApp 1.1.2

MySocialApp 维护。



 
依赖关系
RxSwift~> 3.0.1
RxCocoa~> 3.0.1
RxBlocking~> 3.0.1
Alamofire~> 4.0.1
 

  • 作者:
  • MySocialApp

mysocialapp-swift-client

MySocialApp - 为您的应用提供无缝社交网络功能

官方 Swift 客户端,用于与使用 MySocialApp 创建的应用进行交互

MySocialApp 是什么?

MySocialApp 强大的 API 允许您快速并将无缝地将社交网络功能集成到您的网站、移动和后端应用程序中。我们的 API 每月为数百个应用程序处理数十亿个请求,并能够在 100ms 以内提供响应。

您能做什么?

向现有应用添加社交功能、自动化操作、抓取内容、分析用户内容、将机器人添加到应用中、几乎任何现代社交网络能提供的功能...没有限制!有什么建议可以添加到这里?做 PR 吧。

可用的功能有哪些?

功能 服务器端API Swift客户端API
个人资料管理 ✔️ ✔️
动态 ✔️ ✔️
评论 ✔️ ✔️
点赞 ✔️ ✔️
通知 ✔️ 部分
私密消息 ✔️ ✔️
照片 ✔️ ✔️
用户 ✔️ ✔️
好友 ✔️ ✔️
URL重写 ✔️ ✔️
URL预览 ✔️ ✔️
用户提及 ✔️ ✔️
话题标签 ✔️ ✔️
搜索用户 ✔️ ✔️
搜索动态 ✔️ ✔️
搜索群组 ✔️ ✔️
搜索活动 ✔️ ✔️
群组 [可选模块] ✔️ ✔️
活动 [可选模块] ✔️ ✔️
路线书 [可选模块] ✔️ 部分
使用 RideShare 进行直播跟踪 (示例在这里) [可选模块] ✔️ 即将推出
兴趣点 [可选模块] ✔️ 即将推出
管理员操作 ✔️ 即将推出

正在寻找官方Java/Kotlin客户端API? 点击这里

即将推出

  • 使用FCM(Android)、APNS(iOS)和WebSocket进行实时下游处理。

依赖项

步骤1. 为您的项目激活CocoaPods

pod init

步骤2. 在根Podfile的末尾添加它

target ... {
    ...
  pod 'MySocialApp', '~> 1.1.2'

  post_install do |installer|
    myTargets = ['RxSwift', 'RxCocoa', 'RxBlocking', 'Alamofire', 'MySocialApp']	
    installer.pods_project.targets.each do |target|
      if myTargets.include? target.name
        target.build_configurations.each do |config|
          config.build_settings['SWIFT_VERSION'] = '3.2'
        end
      end
    end
  end
}

步骤3. 更新您的项目CocoaPods

pod update

先决条件

您必须有一个"APP ID"才能定位正确的应用程序。想要创建您的应用程序

应用程序所有者/管理员

登录到go.mysocialapp.io并转到API部分。您的 APP ID 是提供给您的应用程序的端点URL的一部分。它看起来像 https://u123456789123a123456-api.mysocialapp.io。您的 APP IDu123456789123a123456

应用用户

请管理员为您提供 APP ID

使用方法

大部分操作都可以使用 RxSwift 来进行同步和异步处理。我们利用 RxSwift 提供优雅的方式来处理异步结果。

常用用法

每次看到 "try" 指令时,您可以选择这两种不同的方案之一

错误处理

do {
    try MySocialApp.someOperation.throwingException()
} catch let e as MySocialAppException {
    NSLog("Exception caught : \(e.message)")
} catch {
    NSLog("Another technical exception")
}

不处理错误,仅测试是否成功

if let myResult = try? MySocialApp.someOperation.throwingException() {
    doSomething(with: myResult)
} else {
    // Some error occured
}

位置使用

您可以使用 Google Places API 或 Apple MapKit。以下是一个示例,展示如何使用 MapKit 从一个输入字符串中提供匹配的位置列表。

import MapKit
// [..]
let thePlaceToFind: String = "some place somewhere"
let callbackToCallWithFoundLocations: ((_: [Location])->Void) = someCallBackFunction

let request = MKLocalSearchRequest()
request.naturalLanguageQuery = thePlaceToFind
let search = MKLocalSearch(request: request)
search.start {
    response, error in
    if let r = response {
        let locations: [Location] = r.mapItems.map {
            mi in
            let l = Location()
            l.latitude = mi.placemark.coordinate.latitude
            l.longitude = mi.placemark.coordinate.longitude
            if let lines = mi.placemark.addressDictionary?["FormattedAddressLines"] as? [String] {
                // Concatenate every address line, separated by a coma
                var fullName = ""
                var separator = ""
                lines.forEach {
                    fullName += separator + $0
                    separator = ", "
                }
                if let name = mi.placemark.addressDictionary?["Name"] as? String, !fullName.contains(name) {
                    fullName = name + separator + fullName
                }
                // The completeAddress field will contain the fully qualified human-readable location
                l.completeAddress = fullName
            }
            return l
        }
        callbackToCallWithFoundLocations(locations)
    } else {
        callbackToCallWithFoundLocations([])
    }
}

个人资料

创建账户

let appId = "u123456789123a123456"
let msa = MySocialApp.Builder().setAppId(appId).build()

// or
let endpointURL = "https://u123456789123a123456-api.mysocialapp.io";
let msa = MySocialApp.Builder().setAPIEndpointURL(endpointURL).build()

// create an account and return an active session to do fluent operations
let johnSession = try msa.blockingCreateAccount(username: "John", email: "[email protected]", password: "myverysecretpassw0rd")

使用访问令牌登录并获取会话

let johnSession = try msa.blockingConnect(accessToken: "my access token")

使用您的账户登录并获取会话

let johnSession = try msa.blockingConnect(username: "John", password: "myverysecretpassw0rd")

获取您的账户信息

if let account = try johnSession?.account.blockingGet() {
    let _ = account.firstName
    let _ = account.dateOfBirth
    let _ = account.livingLocation?.completeCityAddress
    // [..]
}

更新您的账户

if let account = try johnSession?.account.blockingGet() {
    account.lastName = "James"
    let updatedAccount = try account.blockingSave() // or use save() to asynchronously save it with Rx
}

更新个人照片

let myPhoto = UIImage()
// [..]
try johnSession?.account.blockingChangeProfilePhoto(myPhoto)

更新个人资料封面照片

封面照片是你可以添加到个人资料中的辅助照片。

let myPhoto = UIImage()
// [..]
try johnSession?.account.blockingChangeProfileCoverPhoto(myPhoto)

如何在应用程序中集成 MySocialApp 用户与现有用户?

MySocialApp 允许你使用自己的用户 ID 通过 "external_id" 属性来查找用户。

let yourAppUserId = "12348-abcdy-82739-qzdqdq"

let s = johnSession

// set app external user id
if let account = try johnSession?.account.blockingGet() {
    account.externalId = yourAppUserId
    let updatedAccount = try account.blockingSave()
}

// find user by external id
let user = try johnSession?.user.blockingGetByExternalId(yourAppUserId)

删除您的账户(不可恢复)

⚠ 注意:此操作不可恢复

let s = johnSession
let password = "your account password to confirm the ownership"

let _ = try s?.account.blockingRequestForDeleteAccount(password: password)
// Your account has been deleted..
// You are no more able to perform operations

用户

列出特定位置附近的人

let s = johnSession

let madridLocation = Location(latitude: 40.416775, longitude: -3.703790)
try s?.user.blockingStream(limit: 10, with: FluentUser.Options.Builder().setLocation(madridLocation).build())

新闻动态

从指定页和大小列出新闻流

let feeds = try johnSession?.newsFeed.blockingList(page: 0, size: 10)

流式传输所有100条第一条新闻消息

let feeds = try johnSession?.newsFeed.blockingStream(limit: 100)

发布带有编号、网址和用户提及的公开新闻帖子

let s = johnSession

let post = try FeedPost.Builder()
        .setMessage("This is a post with #hashtag url https://mysocialapp.io and someone mentioned [[user:3856809369215939951]]")
        .setVisibility(.Public)
        .build()

try s?.newsFeed.blockingSendWallPost(post)

使用标签发布公开照片

let s = johnSession
let i = someUIImage

let post = try FeedPost.Builder()
        .setMessage("This is a post with an image and a #hashtag :)")
        .setImage(i)
        .setVisibility(.Public)
        .build()

try s?.newsFeed.blockingSendWallPost(post)

在好友墙上发帖并提及他

let s = johnSession

// take my first friend
if let friend = try s?.account.blockingGet()?.blockingListFriends()?.first {

    let post = try FeedPost.Builder()
        .setMessage("Hey [[user:\(friend.id)]] what's up?")
        .setVisibility(.Friend)
        .build()

    try friend.blockingSendWallPost(post)
}

忽略新闻流帖子

let s = getSession()
if let newsFeed = try s?.newsFeed.blockingStream(limit: 1)?.first {
    try newsFeed.blockingIgnore()
}

举报新闻流帖子

let s = getSession()
if let newsFeed = try s?.newsFeed.blockingStream(limit: 1)?.first {
    try newsFeed.blockingReport()
}

删除新闻动态帖子

let s = getSession()
if let newsFeed = try s?.newsFeed.blockingStream(limit: 1)?.first {
    try newsFeed.blockingDelete()
}

搜索

按姓氏和性别搜索用户

let s = johnSession

let searchQuery = FluentUser.Search.Builder()
        .setFirstName("alice")
        .setGender(.Female)
        .build()

let users = try s?.user.blockingSearch(searchQuery)?.data
// return the 10 first results

按居住地点搜索用户

let s = johnSession

let parisLocation = Location(latitude: 48.85661400000001, longitude: 2.3522219000000177)

let searchQuery = FluentUser.Search.Builder()
        .setLocation(parisLocation)
        .build()

let users = try s?.user.blockingSearch(searchQuery)?.data
// return the 10 first results

搜索包含"hello world"的新闻动态

let s = johnSession

let searchQuery = FluentFeed.Search.Builder()
        .setTextToSearch("hello world")
        .build()

let feeds = try s?.newsFeed.blockingSearch(searchQuery)?.data
// return the 10 first results

私人对话

列出私人对话

let s = johnSession
let conversations = try s?.conversation.blockingList()

创建对话

let s = johnSession

// take 3 first users
if let people = try s?.user.blockingStream(limit: 3) {

    let conversation = Conversation.Builder()
        .setName("let's talk about the next event in private")
        .addMembers(people)
        .build()

    let createdConversation = try s?.conversation.blockingCreate(conversation)
}

将新消息发布到对话

let s = johnSession
let i = someUIImage
if let lastConversation = try s?.conversation.blockingList().first {

    let message = try ConversationMessagePost.Builder()
            .setMessage("Hello, this is a message from our SDK #MySocialApp with an amazing picture. Enjoy")
            .setImage(i)
            .build()

    let messageSent = try lastConversation.blockingSendMessage(message)
}

从对话中获取消息

let s = johnSession
let conversation = try s?.conversation.blockingList().first

// get 35 last messages without consuming them
let conversationMessages = try conversation?.messages?.blockingStream(limit: 35)

// get 35 last messages and consume them
let conversationMessages = try conversation?.messages?.blockingStreamAndConsume(limit: 35)

更改对话名称

let s = johnSession
let conversion = try s?.conversation.blockingList().first

conversion?.name = "new conversation title :)"
try conversion?.blockingSave()

从对话中踢出/邀请成员

let s = johnSession
let conversation = try s?.conversation.blockingList().first

// kick member
try conversation?.blockingKickMember(user)

// invite user
try conversation?.blockingAddMember(user)

给某人发送快速私信

let s = johnSession
let i = someUIImage
if let user = try? s?.user.blockingList().first {

    let message = ConversationMessagePost.Builder()
        .setMessage("Hey [[user:\(user.id)]] ! This is a quick message from our SDK #MySocialApp with an amazing picture. Enjoy")
        .setImage(i)
        .build()

    try user.blockingSendPrivateMessage(message)
}

退出对话

let s = johnSession
if let conversation = try? s?.conversation.blockingList().first {
    try conversation.blockingQuit()
}

事件

本模块为可选模块。请联系我们索取

列出50个下一场活动

let s = johnSession
try s?.event.blockingStream(limit: 50)

创建一个事件

注:设置自定义字段值在自定义字段部分有详细说明。

let s = johnSession
let i = someUIImage

let newarkLocation = Location(longitude: 40.736504474883915, latitude: -74.18175405)
 
let tomorrow = Calendar.current.date(byAdding: Calendar.Component.day, value: 1, to: Date())

let afterTomorrow = Calendar.current.date(byAdding: Calendar.Component.day, value: 2, to: Date())

let customFields = try s?.event.blockingGetAvailableCustomFields().map {
    customField -> (CustomField) in
    if let type = customField.fieldType {
        switch type {
            case .inputText:
                customField.stringValue = "Text test"
            case .inputTextarea:
                customField.stringValue = "TextArea test text"
            case .inputNumber:
                customField.doubleValue = 1337
            case .inputBoolean:
                customField.boolValue = false
            case .inputDate:
                customField.dateValue = Date()
            case .inputUrl:
                customField.stringValue = "https://mysocialapp.io"
            case .inputEmail:
                customField.stringValue = "[email protected]"
            case .inputPhone:
                customField.stringValue = "+33123452345"
            case .inputLocation:
                customField.locationValue = newarkLocation
            case .inputSelect:
                customField.stringValue = customField.possibleValues?.first
            case .inputCheckbox:
                customField.stringsValue = customField.possibleValues ?? []
            case .inputDateTime:
                customField.dateValue = Date()
            case .inputTime:
                customField.dateValue = Date()
            default:
                break
        }
    }
    return customField
}
 
let event = Event.Builder()
        .setName("New test event")
        .setDescription("This is a new event create with our SDK")
        .setStartDate(tomorrow)
        .setEndDate(afterTomorrow)
        .setLocation(newarkLocation)
        .setMaxSeats(100)
        .setMemberAccessControl(.Public)
        .setCoverImage(i)
        .setCustomFields(customFields)
        .build()

try s?.event.blockingCreate(event)

更新一个事件

event.name = "New event name"
try event.save()

参加/参与一个事件

try event.blockingParticipate()

列出我的10个下一个事件

let s = johnSession
try s?.account.blockingGet()?.blockingStreamEvent(limit: 10)

仅限所有者更改事件图片

let i = someUIImage
try event.blockingChangeImage(i)

仅限所有者更改事件封面图片

let i = someUIImage
try event.blockingChangeCoverImage(i)

从特定位置列出最近的事件

let s = johnSession

let madridLocation = Location(latitude: 40.416775, longitude: -3.703790)
try s?.event.blockingStream(limit: 10, with: FluentEvent.Options.Builder().setLocation(madridLocation).build())

在两个日期之间搜索事件

let s = johnSession

let tomorrow = Calendar.current.date(byAdding: Calendar.Component.day, value: 1, to: Date())

let afterTomorrow = Calendar.current.date(byAdding: Calendar.Component.day, value: 2, to: Date())

let madridLocation = Location(latitude: 40.416775, longitude: -3.703790)

let query = FluentEvent.Search.Builder()
        .setLocation(madridLocation)
        .setLocationMaximumDistanceInKilometers(100.0)
        .setFromDate(tomorrow)
        .setToDate(afterTomorrow)
        .setDateField(.startDate)
        .build()

try s?.event.blockingSearch(query)

通过名称或描述搜索事件

let s = johnSession

let query = FluentEvent.Search.Builder()
        .setName("my event name")
        .setDescription("my event description")
        .build()

try s?.event.blockingSearch(query)

通过所有者搜索事件

[..]
try user.blockingStreamEvent(limit: 10)

在事件上创建帖子

[..]
let post = FeedPost.Builder()
        .setMessage("This is a post with #hashtag url https://mysocialapp.io and someone mentioned [[user:3856809369215939951]]")
        .setVisibility(.Public)
        .build()

try event.blockingSendWallPost(post)

群组

此模块为可选。请与我们联系以请求此模块

列出演示组

let s = johnSession
try s?.group.blockingStream(limit: 100)

创建一个群组

let s = johnSession
let i = someUIImage

let newarkLocation = Location(latitude: 40.736504474883915, longitude: -74.18175405)

let group = Group.Builder()
        .setName("New group")
        .setDescription("This is a new group create with our SDK")
        .setLocation(newarkLocation)
        .setMemberAccessControl(.Public)
        .setImage(i)
        .build()

try s?.group.blockingCreate(group)

更新一个群组

group.name = "New group name"
try group.save()

更改群组图像(仅群主)

let i = someUIImage
try group.blockingChangeImage(i)

更改群组封面图像(仅群主)

let i = someUIImage
try group.blockingChangeCoverImage(i)

加入一个群组

try group.blockingJoin()

列出我的群组

let s = johnSession
try s?.account.blockingGet()?.blockingStreamGroup(limit: 10)

列出特定位置的最近群组

let s = johnSession

let madridLocation = Location(latitude: 40.416775, longitude: -3.703790)
try s?.group.blockingStream(limit: 10, with: FluentGroup.Options.Builder().setLocation(madridLocation).build())

按名称或描述搜索群组

let s = johnSession

let query = FluentGroup.Search.Builder()
        .setName("my group name")
        .setDescription("my group description")
        .build()

try s?.group.blockingSearch(query)

按所有者搜索群组

[..]
try user.blockingStreamGroup(limit: 10)

在群组中创建帖子

[..]
let post = FeedPost.Builder()
        .setMessage("This is a post with #hashtag url https://mysocialapp.io and someone mentioned [[user:3856809369215939951]]")
        .setVisibility(.Public)
        .build()

try group.blockingSendWallPost(post)

自定义字段

此功能适用于用户、事件、群组和其他选项,允许您的社区提供特定信息。此功能可以在您的MySocialApp管理控制台进行管理。

显示用户的全部自定义字段

let s = johnSession
if let user = try s?.user.blockingList().first {
    try user.blockingGetCustomFields().forEach {
        field in
        // NB: label, placeholder and string values are automatically translated into the user's language
        NSLog("Custom Field label: \(field.label)")
        // Every type of Custom Field may have a placeholder
        NSLog("Custom Field placeholder: \(field.placeholder)")
        if let type = field.fieldType {
            NSLog("Custom Field type: \(type)")
            if type == FieldType.inputSelect || type == FieldType.inputCheckbox {
                // For SELECT and CHECKBOX types, the list of possible values is provided
                NSLog("CustomField possible values: \(field.possibleValues)")
            }
            // The way the value can be get / set depends on the type of the Custom Field
            switch type {
                case .inputBoolean:
                    NSLog("Custom Field value: \(field.boolValue)")
                case .inputDate, .inputDateTime, .inputTime:
                    NSLog("Custom Field value: \(field.dateValue)")
                case .inputCheckbox:
                    NSLog("Custom Field values: \(field.stringsValue)")
                case .inputUrl, .inputText, .inputEmail, .inputPhone, .inputSelect, .inputTextarea:
                    NSLog("Custom Field value: \(field.stringValue)")
                case .inputLocation:
                    NSLog("Custom Field value: \(field.locationValue)")
                case .inputNumber:
                    NSLog("CustomField value: \(field.doubleValue)")
            }
        }
    }
}

在分组自定义字段上设置位置和URL

let newarkLocation = Location(latitude: 40.736504474883915, longitude: -74.18175405)
let url = "https://mysocialapp.io"

if let group = try s?.group.blockingList().first {
    if let locationField = try group.blockingGetCustomFields().filter({
                group in
                return group.fieldType == FieldType.inputLocation
            }).first {
        locationField.locationValue = newarkLocation
    }

    if let urlField = try group.blockingGetCustomFields().filter({
                group in
                return group.fieldType == FieldType.inputUrl
            }).first {
        urlField.stringValue = url
    }

    try group.blockingSave()
}

实时通知

为了使您的应用程序能够从我们的后端接收原生和静默通知,请遵循以下步骤。

创建.p12证书

原因?我们必须向APNS提供一个与您的应用程序相关的有效证书。

创建APNS证书

  • 登录您的Apple开发者帐户,然后进入“证书、标识符和配置文件”部分,在“证书 > 所有”标签(即在该URL上 此URL
  • 点击“+”按钮以创建新证书
  • 选择“Apple Push Notification服务SSL(沙盒和生产)”,然后点击“继续”
  • 在列表中选择您的App ID,然后点击“继续”
  • 按照指示创建CSR
  • 点击“继续”
  • 选择您刚刚创建的CSR并点击“继续”
  • 下载生成的证书

创建第一个.p12文件

  • 双击您刚刚下载的证书,这将打开您的钥匙串管理器
  • 在“我的证书”列表中搜索一个名为“Apple Push Services: {您的App ID}”的证书
  • 右键单击它,并选择“导出 ...”,将其导出为.p12文件
  • 需要输入密码,因此请输入“mysocialapp”(仅小写)

将 .p12 文件转换为可用的文件

  • 在命令行(终端)中,在包含 .p12 文件的文件夹中,只需键入以下指令,每次提示时输入“mysocialapp”作为密码(仅小写)。
# These instructions require a Java Development Kit (JDK) installed on your system
keytool -importkeystore -destkeystore mysocialapp.jks -srckeystore {your .p12 exported certificat}.p12  -srcstoretype PKCS12
keytool -importkeystore -srckeystore mysocialapp.jks -srcstoretype JKS -deststoretype PKCS12 -destkeystore mysocialapp.p12
openssl base64 -in mysocialapp.p12 -out mysocialapp.b64

上传 .p12 文件

  • 连接到您的 管理员控制台
  • 点击您的应用
  • 选择“证书”选项卡
  • 点击“+添加”按钮
  • 输入您的包名(应用 ID)
  • 选择 iOS 作为平台
  • 输入过期日期
  • 复制/粘贴文件内容到字段中(在文本编辑器中打开文件“mysocialapp.b64”以进行操作)
  • 点击“添加”按钮,完成操作!

使您的应用可接收通知

现在您需要调整您的应用以在我们的后端进行注册,并为目标提供回调,以便在接收到通知时或用户点击本地通知以在您的应用中打开时通知您

启用应用的通知

在 XCode 的项目属性中,转到主目标“能力”,并启用“推送通知”、“后台模式”,在“后台模式”中检查“后台获取”和“远程通知”

允许应用接收通知

您需要请求用户允许通知。只需将以下代码添加到请求用户允许发送通知的地方。

if #available(iOS 10, *) {
    DispatchQueue.main.async {
        UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){
            (granted, error) in
            UNUserNotificationCenter.current().delegate = self
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
} else {
    DispatchQueue.main.async {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
}

在我们的后端注册您的应用

一旦用户同意权限,并且应用程序已注册远程通知,您需要通过实现某些方法接收APNS令牌并发送到我们的后端。

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let msa = MySocialApp.Builder().setAppId(appId).build()
    do {
        let johnSession = try msa.blockingConnect(accessToken: "user access token stored in user defaults or wherever")
        try johnSession.notification.blockingRegisterToken(deviceToken)
    } catch let e as MySocialAppException {
        NSLog("Exception caught : \(e.message)")
    } catch {
        NSLog("Another technical exception")
    }
}

如果用户明确登出,您可以注销令牌以避免用户收到不想要的推送通知。

try johnSession.notification.blockingUnregisterToken()

只为前台和后台模式提供静默通知的回调

您需要在这些方法中实现 AppDelegate.swift 文件。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // [..]
    let msa = MySocialApp.Builder().setAppId(appId).build()
    do {
        let johnSession = try msa.blockingConnect(accessToken: "user access token stored in user defaults or wherever")
        if let receivedNotification = try johnSession.notification.application(didFinishLaunchingWithOptions: launchOptions) {
            // [..] A notification has just been received, you may update the app GUI to notify the user
        } else {
            // Nothing happened, it is a regular application start
        }
    } catch let e as MySocialAppException {
        NSLog("Exception caught : \(e.message)")
    } catch {
        NSLog("Another technical exception")
    }
    // [..]
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    let msa = MySocialApp.Builder().setAppId(appId).build()
    do {
        let johnSession = try msa.blockingConnect(accessToken: "user access token stored in user defaults or wherever")
        if let receivedNotification = try johnSession.notification.application(didReceiveRemoteNotification: userInfo) {
            // [..] The notification has just been received, you may update the app GUI to notify the user
        } else {
            // It wasn't a MySocialApp notification
        }
    } catch let e as MySocialAppException {
        NSLog("Exception caught : \(e.message)")
    } catch {
        NSLog("Another technical exception")
    }
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    let msa = MySocialApp.Builder().setAppId(appId).build()
    do {
        let johnSession = try msa.blockingConnect(accessToken: "user access token stored in user defaults or wherever")
        if let receivedNotification = try johnSession.notification.application(didReceiveRemoteNotification: userInfo) {
            // [..] The notification has just been received, you may update the app GUI to notify the user
        } else {
            // It wasn't a MySocialApp notification
        }
    } catch let e as MySocialAppException {
        NSLog("Exception caught : \(e.message)")
    } catch {
        NSLog("Another technical exception")
    }
    completionHandler(.noData)
}

为用户点击的本地通知提供回调

为了正确处理本地通知上的操作,您首先必须设置应用程序以接收为您的 MySocialApp appId 生成的特定URL。为此,您需要编辑 Info.plist 文件,在主标记中添加以下行,用您的appId替换“u123456789123a123456”。

<key>CFBundleURLTypes</key>
<array><dict>
<key>CFBundleURLSchemes</key>
<array>
<string>u123456789123a123456</string>
</array>
</dict></array>

然后,可以在 AppDelegate.swift 文件中通过实现这些方法捕获本地通知上的操作。

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
    let msa = MySocialApp.Builder().setAppId(appId).build()
    do {
        let johnSession = try msa.blockingConnect(accessToken: "user access token stored in user defaults or wherever")
        if let tappedNotification = try johnSession.notification.application(continue: userActivity) {
            // [..] The notification has just been tapped by the user, you may do something with the notification, like displaying it
        } else {
            // It wasn't a MySocialApp notification
        }
    } catch let e as MySocialAppException {
        NSLog("Exception caught : \(e.message)")
    } catch {
        NSLog("Another technical exception")
    }
    return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let msa = MySocialApp.Builder().setAppId(appId).build()
    do {
        let johnSession = try msa.blockingConnect(accessToken: "user access token stored in user defaults or wherever")
        if let tappedNotification = try johnSession.notification.application(open: url) {
            // [..] The notification has just been tapped by the user, you may do something with the notification, like displaying it
        } else {
            // It wasn't a MySocialApp notification
        }
    } catch let e as MySocialAppException {
        NSLog("Exception caught : \(e.message)")
    } catch {
        NSLog("Another technical exception")
    }
    return true
}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let msa = MySocialApp.Builder().setAppId(appId).build()
    do {
        let johnSession = try msa.blockingConnect(accessToken: "user access token stored in user defaults or wherever")
        if let tappedNotification = try johnSession.notification.userNotificationCenter(didReceive: response) {
            // [..] The notification has just been tapped by the user, you may do something with the notification, like displaying it
        } else {
            // It wasn't a MySocialApp notification
        }
    } catch let e as MySocialAppException {
        NSLog("Exception caught : \(e.message)")
    } catch {
        NSLog("Another technical exception")
    }
}

使用 MySocialApp 的演示应用

鸣谢

贡献

欢迎所有贡献。谢谢