Coder Social home page Coder Social logo

swift's Introduction

PubNub Swift SDK

Platform CocoaPods Compatible Swift Package Manager compatible Carthage Compatible Build Status Codacy Coverage Grade Badge

This is the official PubNub Swift SDK repository.

PubNub takes care of the infrastructure and APIs needed for the realtime communication layer of your application. Work on your app's logic and let PubNub handle sending and receiving data across the world in less than 100ms.

Requirements

  • iOS 9.0+ / macOS 10.11+ / Mac Catalyst 13.0+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 11+
  • Swift 5+

The PubNub Swift SDK doesn't contain any external dependencies.

Get keys

You will need the publish and subscribe keys to authenticate your app. Get your keys from the Admin Portal.

Set up your project

You have several options to set up your project. We provide instructions here for Swift Package Manager, CocoaPods, and Carthage.

  1. Create or open your project inside of Xcode
  2. Navigate to File > Swift Packages > Add Package Dependency
  3. Search for PubNub and select the swift package owned by pubnub, and hit the Next button
  4. Use the Up to Next Major Version rule spanning from 4.0.0 < 5.0.0, and hit the Next button

For more information see Apple's guide on Adding Package Dependencies to Your App

# Podfile
use_frameworks!

target 'YOUR_TARGET_NAME' do
  pod 'PubNubSwift', '~> 4.0'
end

Note: Replace YOUR_TARGET_NAME with your target's name.

In the directory containing your Podfile. execute the following:

pod install

Officially supported: Carthage 0.33 and up.

Add the following to Cartfile:

github "pubnub/swift" ~> 4.0

Then in the directory containing your Cartfile, execute the following:

carthage update

Configure PubNub

  1. Import the module named PubNub inside your AppDelegate:

    import UIKit
    import PubNub // <- Here is our PubNub module import.
  2. Create and configure a PubNub object:

    var config = PubNubConfiguration(
      publishKey: "myPublishKey",
      subscribeKey: "mySubscribeKey",
      uuid: "myUniqueUUID"
    )
    let pubnub = PubNub(configuration: config)

Add event listeners

// Create a new listener instance
let listener = SubscriptionListener()

// Add listener event callbacks
listener.didReceiveSubscription = { event in
  switch event {
  case let .messageReceived(message):
    print("Message Received: \(message) Publisher: \(message.publisher ?? "defaultUUID")")
  case let .connectionStatusChanged(status):
    print("Status Received: \(status)")
  case let .presenceChanged(presence):
    print("Presence Received: \(presence)")
  case let .subscribeError(error):
    print("Subscription Error \(error)")
  default:
    break
  }
}

// Start receiving subscription events
pubnub.add(listener)

NOTE: You can check the UUID of the publisher of a particular message by checking the message.publisher property in the subscription listener. You must also provide a default value for publisher, as the UUID parameter is optional.

Publish and subscribe

pubnub.publish(channel: "my_channel", message: "Test Message!") { result in
  switch result {
  case let .success(timetoken):
    print("The message was successfully published at: \(timetoken)")
  case let .failure(error):
    print("Handle response error: \(error.localizedDescription)")
  }
}

pubnub.subscribe(to: ["my_channel"])

Documentation

Support

If you need help or have a general question, contact [email protected].

License

The PubNub Swift SDK is released under the PubNub Software Development Kit License.

See LICENSE for details.

swift's People

Contributors

craigln avatar davidnub avatar dependabot[bot] avatar jguz-pubnub avatar michaljolender avatar parfeon avatar samiahmedsiddiqui avatar seba-aln avatar techwritermat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swift's Issues

Some PubNub.xcodeproj targets set `TARGETED_DEVICE_FAMILY` that conflicts with `SUPPORTED_PLATFORMS`, preventing building for specific simulators

I've observed this problem for PubNubSpace, PubNubUser, and PubNubMembership.

To reproduce:

  1. Find the device ID of an affected simulator, like a watchOS simulator, with a command like: xcrun simctl list devices 'Apple Watch Series 9 (41mm)'. In my case, the device ID is AA65EFA4-F386-4C67-9AD1-FE86DDC6EC2A.
  2. Attempt to build PubNubUser for that simulator, with a command like the following:
xcodebuild -workspace PubNub.xcworkspace -scheme PubNubUser -sdk watchsimulator -destination platform=watchOS\ Simulator,id=AA65EFA4-F386-4C67-9AD1-FE86DDC6EC2A build

This command will fail with:

xcodebuild: error: Unable to find a destination matching the provided destination specifier:
		{ platform:watchOS Simulator, id:AA65EFA4-F386-4C67-9AD1-FE86DDC6EC2A }

The available destinations notably include iOS simulators, but not watchOS or tvOS simulators.

This behavior does not happen for the PubNub framework.

The cause appears to be that these frameworks set SUPPORTED_PLATFORMS to include watchOS and tvOS, by inheriting the default setting from the project:

SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator watchos watchsimulator";

However, they also set TARGETED_DEVICE_FAMILY to only iPhone (1) and iPad (2):

TARGETED_DEVICE_FAMILY = "1,2";

In contrast, for the PubNub target, TARGETED_DEVICE_FAMILY is set to include tvOS (3) and watchOS (4):

TARGETED_DEVICE_FAMILY = "1,2,3,4";

Removing that setting or setting it to include tvOS and watchOS fixes the issue.

Notably, the repro steps here are comparable to the steps Carthage performs for carthage build --no-skip-current --use-xcframeworks, which also reproduces this issue and impacts us weirdos still using Carthage.

Application with the latest PubNub SDK is crashing.

So there is a crash on iOS 15.
iOS 16-17 - everything works fine.

Report:

Incident Identifier: 5B3D3038-FB20-4856-A4F2-5432AC214D19
Hardware Model:      iPhone9,3
Process:             WalkenWalletProd [379]
Path:                /private/var/containers/Bundle/Application/C83D1F62-6807-43CC-9B57-49B9E4AA3237/WalkenWalletProd.app/WalkenWalletProd
Identifier:          com.walken.quasark
Version:             1.2.0 (220)
AppStoreTools:       15C5500a
AppVariant:          1:iPhone9,3:15
Beta:                YES
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.walken.quasark [576]

Date/Time:           2024-02-13 14:33:24.3487 +0300
Launch Time:         2024-02-13 14:33:24.0771 +0300
OS Version:          iPhone OS 15.6 (19G71)
Release Type:        User
Baseband Version:    6.03.01
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Reason: DYLD 4 Symbol missing
Symbol not found: (_swift_getExtendedExistentialTypeMetadata_unique)
Referenced from: '/Volumes/VOLUME/*/WalkenWalletProd.app/Frameworks/PubNub.framework/PubNub'
Expected in: '/usr/lib/swift/libswiftCore.dylib'
(terminated at launch; ignore backtrace)

Triggered by Thread:  0


Thread 0 Crashed:
0   dyld                           0x0000000102d4f2cc __abort_with_payload + 8 (:-1)
1   dyld                           0x0000000102d546dc abort_with_payload_wrapper_internal + 100 (terminate_with_reason.c:102)
2   dyld                           0x0000000102d5470c abort_with_payload + 12 (terminate_with_reason.c:124)
3   dyld                           0x0000000102d28aa8 dyld4::halt(char const*) + 576 (DyldProcessConfig.cpp:2102)
4   dyld                           0x0000000102d25e44 dyld4::prepare(dyld4::APIs&, dyld3::MachOAnalyzer const*) + 3108 (dyldMain.cpp:0)
5   dyld                           0x0000000102d244b0 start + 412 (dyldMain.cpp:864)


Thread 0 crashed with ARM Thread State (64-bit):
    x0: 0x0000000000000006   x1: 0x0000000000000004   x2: 0x000000016dc396c8   x3: 0x00000000000000ef
    x4: 0x000000016dc392c8   x5: 0x0000000000000000   x6: 0x0000000000000000   x7: 0x000000016dc38d50
    x8: 0x0000000000000020   x9: 0x0000000000000009  x10: 0x000000016dc393ba  x11: 0x0000000000000113
   x12: 0x2f736b726f77656d  x13: 0x662e62754e627550  x14: 0x6b726f77656d6172  x15: 0x0062754e6275502f
   x16: 0x0000000000000209  x17: 0x0000000000000057  x18: 0x0000000000000000  x19: 0x0000000000000000
   x20: 0x000000016dc392c8  x21: 0x00000000000000ef  x22: 0x000000016dc396c8  x23: 0x0000000000000004
   x24: 0x0000000000000006  x25: 0x000000016dc392c8  x26: 0x0000000000000400  x27: 0x0000000000000400
   x28: 0x00000000000000f2   fp: 0x000000016dc39290   lr: 0x0000000102d546dc
    sp: 0x000000016dc39250   pc: 0x0000000102d4f2cc        cpsr: 0x0
   esr: 0x56000080  Address size fault


Binary Images:
        0x102d0c000 -         0x102d5ffff dyld arm64  <c7b2bef37f6b36eb80edcc49f96b9bee> /usr/lib/dyld

EOF

PubNub.add(_:) - $specialized Set._Variant.update(with:)

We are getting a random crash when we call PubNub.add(_:)
It is not 100% reproducible

We have a class with this variable:
let listener: SubscriptionListener

We set the value of listener var in the init of the class:

init(keys: PubnubKeys, email: String) {
        // Setup PNConfiguration
        var configuration = PubNubConfiguration(publishKey: keys.publishKey, subscribeKey: keys.subscriptionKey, uuid: email)
        configuration.authKey = keys.token
        pubnub =  PubNub(configuration: configuration)
        listener = SubscriptionListener(queue: .main)
        pubnub.add(listener)
        ...

This is the stack trace from the crash report:
Screen Shot 2023-02-15 at 11 19 20

We are currently working with PubNub 6.0.3

Can't integrate with swift5

I developed a chat app using SwiftUI and the compiler language in Swift5.

When I build the project, an error is shown as below.

error message

key path value type 'AnyJSON' cannot be converted to contextual type 'JSONCodable'


error related code

    route(router,
          responseDecoder: PresenceResponseDecoder<AnyPresencePayload<AnyJSON>>(),
          custom: requestConfig) { result in
        completion?(result.map(\.payload.payload))

This error locates at setPresence function.

I will give any future information if needed.

Thanks everyone

Crash: partial apply for closure #1 in SessionListener.emitRequest(_:didComplete:with:)

PubNub SDK version: 6.0.5

PubNub SDK is crashing the app SessionListener.emitRequest(_:didComplete:with:), it seems like the object is deallocated before its accessed causing the crash, it could be either request or task or error object that's already deallocated and accessed inside the async { }.

  func emitRequest(_ request: RequestReplaceable, didComplete task: URLSessionTask, with error: Error) {
    queue.async { [weak self] in self?.didCompleteTaskWithError?(request, task, error) }
  }

here are the crash logs,


Crashed: com.pubnub.subscription.response
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x00002920b3fa5e30

Crashed: com.pubnub.subscription.response
0  libswiftCore.dylib             0x3fd43c swift_unknownObjectRelease + 20
1  HomePass                       0x8c6490 partial apply for closure #1 in SessionListener.emitRequest(_:didComplete:with:) + 4353942672 (<compiler-generated>:4353942672)
2  libswiftCore.dylib             0x3a70ec _swift_release_dealloc + 56
3  libswiftCore.dylib             0x3a8788 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1> >::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 136
4  libsystem_blocks.dylib         0x2120 _call_dispose_helpers_excp + 48
5  libsystem_blocks.dylib         0x1d5c _Block_release + 252
6  libdispatch.dylib              0x4300 _dispatch_client_callout + 20
7  libdispatch.dylib              0xb894 _dispatch_lane_serial_drain + 748
8  libdispatch.dylib              0xc3c4 _dispatch_lane_invoke + 380
9  libdispatch.dylib              0x17004 _dispatch_root_queue_drain_deferred_wlh + 288
10 libdispatch.dylib              0x16878 _dispatch_workloop_worker_thread + 404
11 libsystem_pthread.dylib        0xe50 _pthread_wqthread + 288
12 libsystem_pthread.dylib        0xbf0 start_wqthread + 8

Building example app fails if the repo is checked out as directory with a name besides "swift"

Repro steps:

  1. git clone https://github.com/pubnub/swift.git PubNub
  2. open PubNub/PubNub.xcworkspace
  3. Select "Example-iOS" scheme and build

The build will fail with:

Missing package product ...
Package resolution errors must be fixed before building

Inspecting the "Resolve Packages" action shows that it failed with:

unable to override package 'PubNub' because its identity 'swift' doesn't match override's identity (directory name) 'pubnub'

It appears that this happens because the example app adds PubNub as a remote package reference and overrides that with a local package reference. SPM appears to only allow this when the local package is in a directory whose name matches the last component of the remote repo URL.

Removing the remote package reference (and using the local package directly instead) seems to fix this issue.

PubNubPackage schemes reference missing targets, cause DVTAssertion failure in Xcode 14 beta which prevents Carthage builds

The PubNubPackageDescription and PubNubPackageTests schemes reference missing targets:

Screen Shot 2022-08-04 at 3 42 25 PM

A quick grep of the repo suggests these schemes may be unused.

Surprisingly, this also triggers some sort of bug in Xcode 14 beta 4. You can reproduce this by running carthage build --no-skip-current in the repo, which results in the following error:

A shell task (/usr/bin/xcrun xcodebuild -project PubNub.xcodeproj -scheme PubNubPackageTests -configuration Release CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES archive -showBuildSettings -skipUnavailableActions) failed with exit code 6:
2022-08-04 15:37:54.280 xcodebuild[7575:16759252] [MT] DVTAssertions: ASSERTION FAILURE in /System/Volumes/Data/SWE/Apps/DT/BuildRoots/BuildRoot8/ActiveBuildRoot/Library/Caches/com.apple.xbs/Sources/IDEFrameworks/IDEFrameworks-21322/IDEFoundation/Execution/RunDestinations/IDERunDestinationCLI.m:566
Details:  Unhandled/unexpected case where no run destinations were produced.
Object:   <IDERunDestinationCLI>
Method:   +resolveRunDestinationsWithWorkspace:scheme:buildAction:schemeCommand:schemeTask:destinationSpecifications:architectures:timeout:runDestinationManager:deviceManager:fallbackPreferredSDK:fallbackPreferredArchitectures:skipUnsupportedDestinations:shouldSkipRunDestinationValidation:didDisambiguate:disambiguatedMatches:disambiguatedMatchesDescription:error:
Thread:   <_NSMainThread: 0x600001a3c1c0>{number = 1, name = main}
Hints: 

Backtrace:
  0   -[DVTAssertionHandler handleFailureInMethod:object:fileName:lineNumber:assertionSignature:messageFormat:arguments:] (in DVTFoundation)
  1   _DVTAssertionHandler (in DVTFoundation)
  2   _DVTAssertionFailureHandler (in DVTFoundation)
  3   _sortDevicesForDisplay (in IDEFoundation)
  4   -[Xcode3CommandLineBuildTool _resolveRunDestinationsForBuildAction:] (in Xcode3Core)
  5   -[Xcode3CommandLineBuildTool _resolveInputOptionsWithTimingSection:] (in Xcode3Core)
  6   -[Xcode3CommandLineBuildTool run] (in Xcode3Core)
  7   XcodeBuildMain (in libxcodebuildLoader.dylib)
  8   start (in dyld)

(This can also be observed by just running the underlying xcode command that Carthage runs, xcodebuild -project PubNub.xcodeproj -scheme PubNubPackageDescription archive -showBuildSettings -skipUnavailableActions.)

If these schemes are truly unused, it seems that removing them prevents the Xcode 14 beta issue from being triggered.

convert a JSONCodable object to JSONCodableScalar

Hi,
I am trying to convert a JSONCodable object to a JSONCodableScalar and this is failing. the object itself is a representation of json data (with nested values as well). how can I make this work in order to set my presence state, I fail in the second guard statement

`
func setState(stateCodable: JsonCodable) {

    let encoder = JSONEncoder()
    guard let data = try? encoder.encode(stateCodable) else {
        return
    }
    guard let state = try? JSONSerialization.jsonObject(with: data) as? [String: JSONCodableScalar] else {
        return
    }
    pubnub.setPresence(
        state: state,
        on: ["channel"]
    ) { result in
        switch result {
        case let .success(response):
          print("Successful Set State Response: \(response)")
        case let .failure(error):
          print("Failed Set State Response: \(error.localizedDescription)")
        }
    }
}

`
thank you

Using multiple PubNub instances is not possible

We have a project with literally many chats (8000+), every chat room has following descriptors (chat id itself "chat.id", read receipt descriptor "read-receipts.%chat.id%)", changes descriptor "chat.%chat.id%.changes")

When I try to subscribe to more than 600 chat rooms at once in this way, I got following error in the console:
[Error 2021-11-22T12:00:54.349Z (Subscribe Response Queue#0X2807C6DC0) {Request.finish(error:)#324}] Request 6C151EEC-1C38-4903-82E5-C5192353687E failed with error URI of the request was too long to be processed for response <NSHTTPURLResponse: 0x28138ca00> { URL: https://ps.pndsn.com/v2/subscribe/sub-c-2c6c2b6e-0543-11e8-a831-aa01b54f8d06/read-receipts.5868,read-receipts.4095,read-receipts.5008,read-receipts.5441,chat.4747.changes,chat.5172.changes,read-receipts.4611,chat.4922.changes,read-receipts.5574,chat.5729.changes,chat.6046.changes,read-receipts.4483,read-receipts.4258,read-receipts.4688,chat.4525.changes,read-receipts.4198,chat.5410.changes,chat.4802.changes, ...

To avoid this I tried to use multiple pubnub instances PubNub(configuration: configuration) and subscribe every instance to 200 or less chats.
But turns out every particular instance becomes subscribed to all channels and it still returns error "414 URI too long".
For example: I created PubNub A, and PubNub B instances, subscribe A to channel 1 and b to channel 2, but when I call subscribedChannels() for A, it returns both 1 and 2, and same for B.

And more. When I use unique SubscriptionListener for every unique PubNub instance, every listener handles event from all channels that I subscribe from any PubNub instance.

Push Notifications are not working

Hi, I am trying to enable the push notifications on iOS but it's not working. I have tried debugging through the "Push Notifications" app and it works fine from there even through from FCM Console on Firebase.

I am using the following method to register the device on channel.
pubnubTemp?.addAPNSDevicesOnChannels([channel], device: token, on: "mybundleID", environment: .production, completion: completion)

However, I have tried listing the registered devices using listAPNSPushChannelRegistrations but that does not seem to work either. Can you help me sort out what is really going on?

Add `push_type` header in PubNubPushConfig struct

I am trying to trigger VOIP notification and as per the PubNub documentation here, we should be able to set push_type but in code there is no such support. The solution is to add push_type header in PubNubPushConfig struct in PubNub sdk

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.