iOS SDK API guide

Last updated:2025-09-25
Expand all
iOS SDK API guide

Tags and aliases API(iOS)

Function description

Warm reminder, please pay attention when setting label aliases. call back result.

only call back Only when the return value is 0 is the setting successful, it can be pushed to the target. Otherwise the server API will return 1011 mistake. All callback functions run on the main thread.

Provide several related API Used to operate aliases (alias) and label (tags)。

These few API Can be found in App Call anywhere.

Alias alias

Give an alias to identify the user who installed the application. to this user in the future Push When sending a message, you can use this alias to specify.
Only one alias can be specified per user.

Within the same application, it is recommended to use different aliases for different users. This way, the user is uniquely identified based on the alias whenever possible.

The system does not limit an alias to specify only one user. If an alias is assigned to multiple users, when sending a message to the specified alias, the server API Messages will be sent to multiple users at the same time.

For example: In a game where a user wants to log in, the alias may be set to userid. During game operation, if it is found that the user has not played the game for 3 days, the user will be userid Call server side API Send a notification to the client to remind the user.

Notice:JiguangAt 2020/03/10 Limit the upper limit of "Alias ​​Settings", allowing up to 10 devices to be bound. If you need a higher limit, please contact business, please read for details announcement

  • JPush Android v3.5.8 and above,JPush iOS v3.3.2 and above versions will return error code:6027。

  • JPush Android v3.5.8 the following,JPush iOS v3.3.2 The following versions will return error codes:6017。

Label tag

Label users who have installed the application. Its purpose is mainly to facilitate developers to issue batches based on tags. Push information.

Multiple tags can be assigned to each user.

Example: game, old_page, women

Add new tag

call this API to add tags, in block Return results in

Note: This interface is to add logic, not overwrite logic.

Supported versions

Versions supported starting from:3.0.6

Interface definition

+ (void)addTags:(NSSet<NSString *> *)tags completion:(JPUSHTagsOperationCompletion)completion seq:(NSInteger)seq;
          + (void)addTags:(NSSet<NSString *> *)tags
 completion:(JPUSHTagsOperationCompletion)completion
        seq:(NSInteger)seq;

        
This code block is shown in the floating window

Parameter description

  • tags

    • cannot be set nil Or an empty set ([NSSet set])
    • The collection member type requirement is NSString type
    • Set at least one per call tag
    • Valid tag composition: letters (case sensitive), numbers, underscores, Chinese characters, special characters @!#$&*+=.|
    • Limit: each tag The name length is limited to 40 bytes and supports up to 1000 indivual tag, but the total length must not exceed 5 K bytes. (To judge the length, you need to use UTF-8 coding)
    • A single device supports at most settings 1000 indivual tag。App overall situation tag Unlimited quantity
  • completion

    • Used for callbacks to return corresponding parameters tags. And return the corresponding status code: 0 for success. For other return codes, please refer to the error code definition.seq The session serial number passed in when calling
  • seq

    • The sequence number passed in during the request will be returned unchanged during the callback.

override tag

call this API To set the label, in block Return results in

Note: This interface covers logic rather than adding logic. Calling this interface will overwrite all previously set tags.

Supported versions

Versions supported starting from:3.0.6

Interface definition

+ (void)setTags:(NSSet<NSString *> *)tags completion:(JPUSHTagsOperationCompletion)completion seq:(NSInteger)seq;
          + (void)setTags:(NSSet<NSString *> *)tags
 completion:(JPUSHTagsOperationCompletion)completion
        seq:(NSInteger)seq;

        
This code block is shown in the floating window

Parameter description

  • tags

    • cannot be set nil Or an empty set ([NSSet set])
    • The collection member type requirement is NSString type
    • Set at least one per call tag
    • Valid tag composition: letters (case sensitive), numbers, underscores, Chinese characters, special characters @!#$&*+=.|
    • Limit: each tag The name length is limited to 40 bytes and supports up to 1000 indivual tag, but the total length must not exceed 5 K bytes. (To judge the length, you need to use UTF-8 coding)
    • A single device supports at most settings 1000 indivual tag。App overall situation tag Unlimited quantity
  • completion

    • Used for callbacks to return corresponding parameters tags. And return the corresponding status code: 0 for success. For other return codes, please refer to the error code definition.seq The session serial number passed in when calling
  • seq

    • The sequence number passed in during the request will be returned unchanged during the callback.

Query tag

Interface definition

+ (void)getAllTags:(JPUSHTagsOperationCompletion)completion seq:(NSInteger)seq;
          + (void)getAllTags:(JPUSHTagsOperationCompletion)completion
        seq:(NSInteger)seq;

        
This code block is shown in the floating window

Parameter description

  • completion

    • callback returned tags for query results. The corresponding status code is returned: 0 for success. For other return codes, please refer to the error code definition.seq The session serial number passed in when calling
  • seq

    • The sequence number passed in during the request will be returned unchanged during the callback.

Verification tag

call this API to verify the target tag Has it been set?

Supported versions

Versions supported starting from:3.0.6

Interface definition

+ (void)validTag:(NSString *)tag completion:(JPUSHTagValidOperationCompletion)completion seq:(NSInteger)seq;
          + (void)validTag:(NSString *)tag
 completion:(JPUSHTagValidOperationCompletion)completion
        seq:(NSInteger)seq;

        
This code block is shown in the floating window

Parameter description

  • tag

    • cannot be set nil or empty string
    • Valid tag composition: letters (case sensitive), numbers, underscores, Chinese characters, special characters @!#$&*+=.|
    • Limit: each tag The name length is limited to 40 bytes (you need to use UTF-8 coding)
  • completion

    • The callback returns the corresponding parameters tag. And return the corresponding status code: 0 for success. For other return codes, please refer to the error code definition.seq The session serial number passed in when calling
    • View in callback isBind Check whether the property has been set,YES is already set
  • seq

    • The sequence number passed in during the request will be returned unchanged during the callback.

Delete tag

call this API to delete the specified tags

Supported versions

Versions supported starting from:3.0.6

Interface definition

+ (void)deleteTag:(NSString *)tag completion:(JPUSHTagsOperationCompletion)completion seq:(NSInteger)seq;
          + (void)deleteTag:(NSString *)tag
 completion:(JPUSHTagsOperationCompletion)completion
        seq:(NSInteger)seq;

        
This code block is shown in the floating window

Parameter description

  • tag

    • cannot be set nil or empty string
    • Valid tag composition: letters (case sensitive), numbers, underscores, Chinese characters, special characters @!#$&*+=.|
    • Limit: each tag The name length is limited to 40 bytes (you need to use UTF-8 coding)
  • completion

    • Used for callbacks to return corresponding parameters tags. And return the corresponding status code: 0 for success. For other return codes, please refer to the error code definition.seq The session serial number passed in when calling
  • seq

    • The sequence number passed in during the request will be returned unchanged during the callback.

Set label callback (Tags Block)

typedef void (^JPUSHTagsOperationCompletion)(NSInteger iResCode, NSSet *iTags, NSInteger seq); typedef void (^JPUSHTagValidOperationCompletion)(NSInteger iResCode, NSSet *iTags, NSInteger seq, BOOL isBind);
          typedef void (^JPUSHTagsOperationCompletion)(NSInteger iResCode, NSSet *iTags, NSInteger seq);
typedef void (^JPUSHTagValidOperationCompletion)(NSInteger iResCode, NSSet *iTags, NSInteger seq, BOOL isBind);

        
This code block is shown in the floating window

Set alias

call this API to set alias

Supported versions

Versions supported starting from:3.0.6

Interface definition

+ (void)setAlias:(NSString *)alias completion:(JPUSHAliasOperationCompletion)completion seq:(NSInteger)seq;
          + (void)setAlias:(NSString *)alias
  completion:(JPUSHAliasOperationCompletion)completion
         seq:(NSInteger)seq;

        
This code block is shown in the floating window

Parameter description

  • alias
    • cannot be set nil Or empty string @""
    • Sets a valid alias for each call, overwriting previous settings.
    • Valid aliases consist of: letters (case sensitive), numbers, underscores, Chinese characters, special characters @!#$&*+=.|
    • limit:alias Name length is limited to 40 bytes. (To judge the length, you need to use UTF-8 coding)
  • completion

    • The callback returns the corresponding parameters alias. And return the corresponding status code: 0 for success. For other return codes, please refer to the error code definition.seq The session serial number passed in when calling
  • seq

    • The sequence number passed in during the request will be returned unchanged during the callback.

Delete alias

call this API to delete the alias, in block Return results in

Supported versions

Versions supported starting from:3.0.6

Interface definition

+ (void)deleteAlias:(JPUSHAliasOperationCompletion)completion seq:(NSInteger)seq;
          + (void)deleteAlias:(JPUSHAliasOperationCompletion)completion
            seq:(NSInteger)seq;

        
This code block is shown in the floating window

Parameter description

  • completion

    • callback returned tags for nil. The corresponding status code is returned: 0 for success. For other return codes, please refer to the error code definition.seq The session serial number passed in when calling
  • seq

    • The sequence number passed in during the request will be returned unchanged during the callback.

Query alias

call this API To query the current alias, in block Return results in

Supported versions

Versions supported starting from:3.0.6

Interface definition

+ (void)getAlias:(JPUSHAliasOperationCompletion)completion seq:(NSInteger)seq;
          + (void)getAlias:(JPUSHAliasOperationCompletion)completion
         seq:(NSInteger)seq;

        
This code block is shown in the floating window

Parameter description

  • completion

    • callback returned tags for query results. The corresponding status code is returned: 0 for success. For other return codes, please refer to the error code definition.seq The session serial number passed in when calling
  • seq

    • The sequence number passed in during the request will be returned unchanged during the callback.

set alias callback(Alias Block)

typedef void (^JPUSHAliasOperationCompletion)(NSInteger iResCode, NSString *iAlias, NSInteger seq);
          typedef void (^JPUSHAliasOperationCompletion)(NSInteger iResCode, NSString *iAlias, NSInteger seq);

        
This code block is shown in the floating window

Set aliases and tags (with Callback)

call this API To set aliases and labels at the same time, support callback functions.

What needs to be understood is that this interface is overwriting logic, not incremental logic. That is, new calls will overwrite previous settings.

After the previous call, if you need to change the alias and label again, you only need to call this again. API That’s it.

Supported versions

Versions supported starting from:1.4.0

Interface definition

+ (void)setTags:(NSSet *)tags alias:(NSString *)alias callbackSelector:(SEL)cbSelector object:(id)theTarget;
          + (void)setTags:(NSSet *)tags alias:(NSString *)alias callbackSelector:(SEL)cbSelector object:(id)theTarget;

        
This code block is shown in the floating window

Parameter description

  • alias
    • nil This call does not set this value.
    • An empty string (@"") means canceling the previous setting.
    • Each call sets a valid alias, overwriting the previous setting.
    • Valid aliases consist of: letters (case sensitive), numbers, underscores, Chinese characters, special characters (2.1.9 Support)@!#$&*+=.|.
    • limit:alias Name length is limited to 40 bytes. (To judge the length, you need to use UTF-8 coding)
  • tags

    • nil This call does not set this value.
    • Empty set ([NSSet set]) means canceling the previous settings.
    • The collection member type requirement is NSString type
    • Set at least one per call tag, overwrite the previous settings, not add new ones.
    • Valid label composition: letters (case sensitive), numbers, underlines, Chinese characters, special characters (2.1.9 Support)@!#$&*+=.|.
    • Limit: each tag The name length is limited to 40 bytes and supports up to 1000 indivual tag, but the total length must not exceed 7 K bytes. (To judge the length, you need to use UTF-8 coding)
    • A single device supports at most settings 1000 indivual tag。App overall situation tag Unlimited quantity.
  • callbackSelector

    • nil Not required for this call Callback。
    • Used for callbacks to return corresponding parameters alias, tags. And return the corresponding status code: 0 for success. For other return codes, please refer to the error code definition.
    • Please refer to the callback function SDK accomplish.
  • theTarget

    • The parameter value is implemented callbackSelector instance object.
    • nil Not required for this call Callback。
-(void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias { NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias); }
          -(void)tagsAliasCallback:(int)iResCode
                    tags:(NSSet*)tags
                   alias:(NSString*)alias
{
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
}

        
This code block is shown in the floating window

Set aliases and tags (background)

call this API Set the alias and label at the same time in the background, without processing the setting results.SDK Will automatically retry on failure

What needs to be understood is that this interface is overwriting logic, not incremental logic. That is, new calls will overwrite previous settings.

After the previous call, if you need to change the alias and label again, you only need to call this again. API That’s it.

It should be noted that the background Mode settings and non- background The settings are two different settings that do not affect each other, which means that neither background The setting will not terminate the current background set unless another background Setup occurs.

Supported versions

Versions supported starting from:2.1.0

Interface definition

+ (void)setTags:(NSSet *)tags aliasInbackground:(NSString *)alias;
          + (void)setTags:(NSSet *)tags aliasInbackground:(NSString *)alias;

        
This code block is shown in the floating window

Parameter description

  • alias
    • nil This call does not set this value.
    • An empty string (@"") means canceling the previous setting.
    • Each call sets a valid alias, overwriting the previous setting.
    • Valid aliases consist of: letters (case sensitive), numbers, underscores, Chinese characters, special characters (2.1.9 Support)@!#$&*+=.|.
    • limit:alias Name length is limited to 40 bytes. (To judge the length, you need to use UTF-8 coding)
  • tags

    • nil This call does not set this value.
    • Empty set ([NSSet set]) means canceling the previous settings.
    • The collection member type requirement is NSString type
    • Set at least one per call tag, overwrite the previous settings, not add new ones.
    • Valid label composition: letters (case sensitive), numbers, underlines, Chinese characters, special characters (2.1.9 Support)@!#$&*+=.|.
    • Limit: each tag The name length is limited to 40 bytes and supports up to 1000 indivual tag, but the total length must not exceed 7 K bytes. (To judge the length, you need to use UTF-8 coding)
    • A single device supports at most settings 1000 indivual tag。App overall situation tag Unlimited quantity.
[JPUSHService setTags:tags aliasInbackground:alias];
          [JPUSHService setTags:tags aliasInbackground:alias];

        
This code block is shown in the floating window

Set aliases and tags (with block)

call this API To set the alias and label at the same time, pass block to return the results of setting aliases and labels.

What needs to be understood is that this interface is overwriting logic, not incremental logic. That is, new calls will overwrite previous settings.

After the previous call, if you need to change the alias and label again, you only need to call this again. API That’s it.

Supported versions

Versions supported starting from:2.1.0

Interface definition

+ (void)setTags:(NSSet *)tags alias:(NSString *)alias fetchCompletionHandle:(void (^)(int iResCode, NSSet *iTags, NSString *iAlias))completionHandler
          + (void)setTags:(NSSet *)tags alias:(NSString *)alias fetchCompletionHandle:(void (^)(int iResCode, NSSet *iTags, NSString *iAlias))completionHandler

        
This code block is shown in the floating window

Parameter description

  • alias
    • nil This call does not set this value.
    • An empty string (@"") means canceling the previous setting.
    • Each call sets a valid alias, overwriting the previous setting.
    • Valid aliases consist of: letters (case sensitive), numbers, underscores, Chinese characters, special characters (2.1.9 Support)@!#$&*+=.|.
    • limit:alias Name length is limited to 40 bytes. (To judge the length, you need to use UTF-8 coding)
  • tags

    • nil This call does not set this value.
    • Empty set ([NSSet set]) means canceling the previous settings.
    • The collection member type requirement is NSString type
    • Set at least one per call tag, overwrite the previous settings, not add new ones.
    • Valid label composition: letters (case sensitive), numbers, underlines, Chinese characters, special characters (2.1.9 Support)@!#$&*+=.|.
    • Limit: each tag The name length is limited to 40 bytes and supports up to 1000 indivual tag, but the total length must not exceed 7 K bytes. (To judge the length, you need to use UTF-8 coding)
    • A single device supports at most settings 1000 indivual tag。App overall situation tag Unlimited quantity.
  • (void (^)(int iResCode, NSSet *iTags, NSString *iAlias))completionHandler

    • completionHandler Used to handle setting return results
    • iResCode Result status code returned
    • iTags and iAlias Returns the set tag and alias
[JPUSHService setTags:tags alias:alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias){ NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, iTags, iAlias); }];
          [JPUSHService setTags:tags alias:alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias){
 NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, iTags, iAlias);
}];

        
This code block is shown in the floating window

Set labels (old)

call this API to set labels and support callback functions.

The method is setTagsWithAlias (with Callback) for changing only labels.

Usage suggestions


If to be set alias / tags is dynamic, it is possible to call setTagsWithAlias time because alias / tags Invalid and the entire call failed.


Calling this method only sets tags, which can exclude possible invalid alias impact on this call.

Supported versions

Versions supported starting from:1.4.0

Interface definition

+ (void)setTags:(NSSet *)tags callbackSelector:(SEL)cbSelector object:(id)theTarget;
          + (void)setTags:(NSSet *)tags callbackSelector:(SEL)cbSelector object:(id)theTarget;

        
This code block is shown in the floating window

Parameter description

  • tags

    • nil This call does not set this value.
    • Empty set ([NSSet set]) means canceling the previous settings.
    • Set at least one per call tag, overwrite the previous settings, not add new ones.
    • Valid label composition: letters (case sensitive), numbers, underlines, Chinese characters, special characters (2.1.9 Support)@!#$&*+=.|.
    • Limit: each tag The name length is limited to 40 bytes and supports up to 1000 indivual tag, but the total length must not exceed 7 K bytes. (To judge the length, you need to use UTF-8 coding)
    • A single device supports at most settings 1000 indivual tag。App overall situation tag Unlimited quantity.
  • callbackSelector

    • nil Not required for this call Callback。
    • Used for callbacks to return corresponding parameters alias, tags. And return the corresponding status code: 0 for success. For other return codes, please refer to the error code definition.
    • Please refer to the callback function SDK accomplish.
  • theTarget

    • The parameter value is implemented callbackSelector instance object.
    • nil Not required for this call Callback。
- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias { NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);}
              - (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
                NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);}

        
This code block is shown in the floating window

Set alias (old)

call this API To set an alias and support callback functions.

The method is setTagsWithAlias (with Callback), used when only the alias is changed.

Supported versions

Versions supported starting from:1.4.0

Interface definition

+ (void)setAlias:(NSString *)alias callbackSelector:(SEL)cbSelector object:(id)theTarget;
              + (void)setAlias:(NSString *)alias callbackSelector:(SEL)cbSelector object:(id)theTarget;

        
This code block is shown in the floating window

Parameter description

  • alias

    • An empty string (@"") means canceling the previous setting.
    • Each call sets a valid alias, overwriting the previous setting.
    • Valid aliases consist of: letters (case sensitive), numbers, underscores, Chinese characters, special characters (2.1.9 Support)@!#$&*+=.|.
    • limit:alias Name length is limited to 40 bytes. (To judge the length, you need to use UTF-8 coding)
  • callbackSelector

    • nil Not required for this call Callback。
    • Used for callbacks to return corresponding parameters alias, tags. And return the corresponding status code: 0 for success. For other return codes, please refer to the error code definition.
    • Please refer to the callback function SDK accomplish.
  • theTarget

    • The parameter value is implemented callbackSelector instance object.
    • nil Not required for this call Callback。
- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias { NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias) }
              - (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
            NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias)        }

        
This code block is shown in the floating window

Filter valid tags

Used to filter out the correct available tags。

If the total quantity exceeds the maximum limit, return the largest quantity available tags。

Usage suggestions


set up tags, if one of the tag If it is invalid, the entire setup process fails.


if App of tags will be set dynamically during operation, and there are JPush SDK tag specified invalid characters, there may be a tag Invalid results in all the tags Update failed.


At this time you can call this method filterValidTags to filter out invalid tags, get a valid tags, then call JPush SDK of set tags / alias method.

Supported versions

Versions supported starting from:1.4.0

Interface definition

+ (NSSet*)filterValidTags:(NSSet*)tags;
          + (NSSet*)filterValidTags:(NSSet*)tags;

        
This code block is shown in the floating window

Parameter description

  • tags
    • Original tag gather.

interface returns

valid tag gather.

Return error code reference: Error code definition

In-app messages

Supported version

v5.0.0 version start

Function description

To use the in-app messaging feature, you need to configure this interface. In-app messages will trigger display logic when the page is switched, and in-app messages can be displayed on a specified page. This interface synchronizes the entry and exit actions of the page to SDK,SDK The display logic of in-app messages will be processed based on this logic.

Interface definition

+ (void)pageEnterTo:(NSString *)pageName + (void)pageLeave:(NSString *)pageName;
          + (void)pageEnterTo:(NSString *)pageName
+ (void)pageLeave:(NSString *)pageName;

        
This code block is shown in the floating window

Call example

Call instructions

Please use it together pageEnterTo: and pageLeave: Interface, called when entering the page pageEnterTo:, called when leaving the page pageLeave: 。

Call example

// 例如可以在 ViewController 的 viewDidAppear: 和 viewDidDisappear: 方法中配套调用 - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [JPUSHService pageEnterTo:@"AViewController"]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [JPUSHService pageLeave:@"AViewController"]; }
          // 例如可以在 ViewController 的 viewDidAppear: 和  viewDidDisappear: 方法中配套调用
- (void)viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
  [JPUSHService pageEnterTo:@"AViewController"];
}

- (void)viewDidDisappear:(BOOL)animated {
  [super viewDidDisappear:animated];
  [JPUSHService pageLeave:@"AViewController"];
}

        
This code block is shown in the floating window

get APNs(Notification) Push content

Supported versions

Initial version.

Function description

iOS The device receives a push (APNs), when the user clicks the push notification to open the application, the application needs to process it according to the status. AppDelegate Add code to the following two methods in to get apn content

  • if App status is not running, this function will be called if launchOptions Include UIApplicationLaunchOptionsRemoteNotificationKey Indicates that the user clicked apn Notification leads to app is started to run; if it does not contain the corresponding key value, it means App Not because of clicks apn And be activated, it may be a direct click icon to be activated or otherwise.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions; // apn 内容获取: NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey]
          - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
// apn 内容获取:
NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey]

        
This code block is shown in the floating window
  • based on iOS 6 and below system versions, if App If the status is in the foreground or click on the notification message in the notification bar, then this function will be called and can be passed AppDelegate of applicationState Is it UIApplicationStateActive Determine whether the program is running in the foreground. This situation is handled in this function:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;
          - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;

        
This code block is shown in the floating window
  • based on iOS 7 and above system versions, if using iOS 7 of Remote Notification properties then the handler function needs to use
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;
          - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;

        
This code block is shown in the floating window
  • based on iOS System versions 10 and above, original [application: didReceiveRemoteNotification:] will be discarded by the system,
    Added by UserNotifications Framework in [UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:]
    or [UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:] method substitution.
    exist 2.1.9 Version and above can be achieved SDK encapsulated JPUSHRegisterDelegate Protocol method, adaptation iOS10 New delegate protocol method.
    That is, the following two methods:
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler; // NSDictionary * userInfo = notification.request.content.userInfo; // APNs 内容为 userInfo - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler; // NSDictionary * userInfo = response.notification.request.content.userInfo; // APNs 内容为 userInfo
          - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler;
// NSDictionary * userInfo = notification.request.content.userInfo;
// APNs 内容为 userInfo

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler;
// NSDictionary * userInfo = response.notification.request.content.userInfo;
// APNs 内容为 userInfo

        
This code block is shown in the floating window

Sample code

// NS_DEPRECATED_IOS(3_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:] for user visible notifications and -[UIApplicationDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:] for silent remote notifications") - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { // 取得 APNs 标准信息内容 NSDictionary *aps = [userInfo valueForKey:@"aps"]; NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容 NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge 数量 NSString *sound = [aps valueForKey:@"sound"]; //播放的声音 // 取得 Extras 字段内容 NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中 Extras 字段,key 是自己定义的 NSLog(@"content =[%@], badge=[%d], sound=[%@], customize field =[%@]",content,badge,sound,customizeField1); // iOS 10 以下 Required [JPUSHService handleRemoteNotification:userInfo]; } //iOS 7 Remote Notification - (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { NSLog(@"this is iOS7 Remote Notification"); // iOS 10 以下 Required [JPUSHService handleRemoteNotification:userInfo]; completionHandler(UIBackgroundFetchResultNewData); } # pragma mark- JPUSHRegisterDelegate // 2.1.9 版新增 JPUSHRegisterDelegate, 需实现以下两个方法 // iOS 10 Support - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler { // Required NSDictionary * userInfo = notification.request.content.userInfo; if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { [JPUSHService handleRemoteNotification:userInfo]; } else { // 本地通知 } completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有 Badge、Sound、Alert 三种类型可以选择设置 } // iOS 10 Support - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)())completionHandler { // Required NSDictionary * userInfo = response.notification.request.content.userInfo; if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { [JPUSHService handleRemoteNotification:userInfo]; } else { // 本地通知 } completionHandler(); // 系统要求执行这个方法 }
          // NS_DEPRECATED_IOS(3_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:] for user visible notifications and -[UIApplicationDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:] for silent remote notifications")
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  // 取得 APNs 标准信息内容
  NSDictionary *aps = [userInfo valueForKey:@"aps"];
  NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
  NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge 数量
  NSString *sound = [aps valueForKey:@"sound"]; //播放的声音

  // 取得 Extras 字段内容
  NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中 Extras 字段,key 是自己定义的
  NSLog(@"content =[%@], badge=[%d], sound=[%@], customize field  =[%@]",content,badge,sound,customizeField1);

  // iOS 10 以下 Required
  [JPUSHService handleRemoteNotification:userInfo];
}

//iOS 7 Remote Notification
- (void)application:(UIApplication *)application didReceiveRemoteNotification:  (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

  NSLog(@"this is iOS7 Remote Notification");

  // iOS 10 以下 Required
  [JPUSHService handleRemoteNotification:userInfo];
  completionHandler(UIBackgroundFetchResultNewData);
}

# pragma mark- JPUSHRegisterDelegate // 2.1.9 版新增 JPUSHRegisterDelegate, 需实现以下两个方法

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center  willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  // Required
  NSDictionary * userInfo = notification.request.content.userInfo;
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
  }
  else {
     // 本地通知
  }
  completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)())completionHandler {
  // Required
  NSDictionary * userInfo = response.notification.request.content.userInfo;
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
  }
  else {
     // 本地通知
  }
  completionHandler();  // 系统要求执行这个方法
}

        
This code block is shown in the floating window
  • based on iOS12 The above version,UserNotifications Framework Added callback method [userNotificationCenter:openSettingsForNotification:], exist 3.1.1 and above JPUSHRegisterDelegate A corresponding callback method has also been added. This method will be called when the application is entered from the external notification interface or the notification settings interface.
// iOS 12 Support - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{ if (notification) { //从通知界面直接进入应用 }else{ //从通知设置界面进入应用 } }
          // iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
  if (notification) {
    //从通知界面直接进入应用
  }else{
    //从通知设置界面进入应用
  }
}

        
This code block is shown in the floating window

Reference documentation: Handling Local and Remote Notifications

Get custom message push content

Supported versions

r1.2.5 after.

Function description

Custom message push can only be received when the front end is running.

from JPush The server obtains the custom message content and title pushed by the user, as well as additional fields, etc.

Implementation method

get iOS The push content needs to be in delegate Register notifications and implement callback methods in the class.

in method-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *) launchOptions Add the following code:

NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter]; [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
              NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];

        
This code block is shown in the floating window

Implement callback method networkDidReceiveMessage

- (void)networkDidReceiveMessage:(NSNotification *)notification {     NSDictionary * userInfo = [notification userInfo];     NSString *content = [userInfo valueForKey:@"content"];     NSString *messageID = [userInfo valueForKey:@"_j_msgid"]; NSDictionary *extras = [userInfo valueForKey:@"extras"];     NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的 Extras 附加字段,key 是自己定义的   }
              - (void)networkDidReceiveMessage:(NSNotification *)notification {
        NSDictionary * userInfo = [notification userInfo];
        NSString *content = [userInfo valueForKey:@"content"];
        NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
        NSDictionary *extras = [userInfo valueForKey:@"extras"];
        NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的 Extras 附加字段,key 是自己定义的  
    }

        
This code block is shown in the floating window

Parameter description:

content: Get pushed content

messageID: Get pushed messageID(key for @"_j_msgid")

extras: Get user-defined parameters

customizeField1: According to customization key Get custom value

More implementation references SDK Download compressed package in demo。

Get in-app reminder push content

Supported versions

v4.6.0 and subsequent versions

Function description

In-app reminder: When sending a notification, a local notification will be used instead of a push notification for target users who have turned off notification permissions.

only in APP You can only receive in-app reminder messages when it is running in the foreground. To use this feature, you need to turn on the "in-app reminder" switch in the advanced settings of push notifications on the push platform.

By setting the proxy for the in-app reminder function and implementing the corresponding proxy method, you can obtain the content title and additional fields of the in-app reminder.

Implementation method

Add to Delegate

@interface AppDelegate ()<JPushNotiInMessageDelegate> @end
          @interface AppDelegate ()<JPushNotiInMessageDelegate>

@end

        
This code block is shown in the floating window

Set proxy

Please add the following code to -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

[JPUSHService setNotiInMessageDelegate:self];
          [JPUSHService setNotiInMessageDelegate:self];

        
This code block is shown in the floating window

Add a proxy method for in-app reminder callbacks

#pragma mark - JPushNotiInMessageDelegate // 应用内提醒展示的回调 - (void)jPushNotiInMessageDidShowWithContent:(NSDictionary *)content { NSString *messageID = [content valueForKey:@"_j_msgid"]; NSDictionary *aps = [content valueForKey:@"aps"]; id customizeField1 = [content valueForKey:@"customizeField1"]; // 推送平台高级设置里的附加字段的 key } // 应用内提醒点击的回调 - (void)jPushNotiInMessageDidClickWithContent:(NSDictionary *)content { NSString *messageID = [content valueForKey:@"_j_msgid"]; NSDictionary *aps = [content valueForKey:@"aps"]; id customizeField1 = [content valueForKey:@"customizeField1"]; // 推送平台高级设置里的附加字段的 key }
          #pragma mark - JPushNotiInMessageDelegate

// 应用内提醒展示的回调
- (void)jPushNotiInMessageDidShowWithContent:(NSDictionary *)content {
  NSString *messageID = [content valueForKey:@"_j_msgid"];
  NSDictionary *aps = [content valueForKey:@"aps"];
  id customizeField1 = [content valueForKey:@"customizeField1"]; // 推送平台高级设置里的附加字段的 key
}

// 应用内提醒点击的回调
- (void)jPushNotiInMessageDidClickWithContent:(NSDictionary *)content {
  NSString *messageID = [content valueForKey:@"_j_msgid"];
  NSDictionary *aps = [content valueForKey:@"aps"];
  id customizeField1 = [content valueForKey:@"customizeField1"]; // 推送平台高级设置里的附加字段的 key
}

        
This code block is shown in the floating window

Parameter description:

  • messageID: Get pushed (key for @"_j_msgid”)

  • aps: Get pushed content

  • customizeField1: According to customization key Get custom value (Additional fields in the advanced settings of the push platform are customized. key)

Get in-app message push content

Supported versions

v5.0.0 and subsequent versions

Function description

In-app message:APP In-app messages can only be received when running in the foreground. There are now three types of in-app messages, banner, interstitial, and full screen.

By setting the proxy for the in-app messaging function and implementing the corresponding proxy method, you can obtain the content of the in-app message.

Implementation method

Add to Delegate

@interface AppDelegate ()<JPUSHInAppMessageDelegate> @end
          @interface AppDelegate ()<JPUSHInAppMessageDelegate>

@end

        
This code block is shown in the floating window

Set proxy

Please add the following code to -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

[JPUSHService setInAppMessageDelegate:self];
          [JPUSHService setInAppMessageDelegate:self];

        
This code block is shown in the floating window

Add a proxy method for in-app message callbacks

#pragma mark - JPushInAppMessageDelegate // 展示回调 - (void)jPushInAppMessageDidShow:(JPushInAppMessage *)inAppMessage { NSString *messageId = inAppMessage.mesageId; NSString *title = inAppMessage.title; NSString *content = inAppMessage.content; // ... 更多参数获取请查看 JPushInAppMessage NSLog(@"jPushInAppMessageDidShow - messageId:%@, title:%@, content:%@",messageId,title,content); } // 点击回调 - (void)jPushInAppMessageDidClick:(JPushInAppMessage *)inAppMessage { NSString *messageId = inAppMessage.mesageId; NSString *title = inAppMessage.title; NSString *content = inAppMessage.content; // ... 更多参数获取请查看 JPushInAppMessage NSLog(@"jPushInAppMessageDidClick - messageId:%@, title:%@, content:%@",messageId,title,content); }
          #pragma mark - JPushInAppMessageDelegate
// 展示回调
- (void)jPushInAppMessageDidShow:(JPushInAppMessage *)inAppMessage {
  NSString *messageId = inAppMessage.mesageId;
  NSString *title = inAppMessage.title;
  NSString *content = inAppMessage.content;
  // ... 更多参数获取请查看 JPushInAppMessage
  NSLog(@"jPushInAppMessageDidShow - messageId:%@, title:%@, content:%@",messageId,title,content);
}

// 点击回调
- (void)jPushInAppMessageDidClick:(JPushInAppMessage *)inAppMessage {
  NSString *messageId = inAppMessage.mesageId;
  NSString *title = inAppMessage.title;
  NSString *content = inAppMessage.content;
  // ... 更多参数获取请查看 JPushInAppMessage
  NSLog(@"jPushInAppMessageDidClick - messageId:%@, title:%@, content:%@",messageId,title,content);
}

        
This code block is shown in the floating window

get RegistrationID

RegistrationID definition

Integrated JPush SDK The application is successfully registered for the first time to JPush When the serverJPush The server will return a unique identifier of the device to the client - RegistrationID。JPush SDK will be sent as a broadcast RegistrationID to the application.

Applications can use this RegistrationID Save it on your own application server, and then you can RegistrationID to push messages or notifications to the device.

get registrationID(with block)

Supported versions

Versions supported starting from:2.1.9。

Interface definition

+ (void)registrationIDCompletionHandler:(void(^)(int resCode,NSString *registrationID))completionHandler;
          + (void)registrationIDCompletionHandler:(void(^)(int resCode,NSString *registrationID))completionHandler;

        
This code block is shown in the floating window

Parameter description

  • (void(^)(int resCode,NSString *registrationID))completionHandler
  • completionHandler Used to handle setting return results
  • resCode Result status code returned
  • registrationID return registrationID
[JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) { NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID); }];
          [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
    NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID);
}];

        
This code block is shown in the floating window

Kind tips:


It is recommended to use this interface to obtain registrationID, call this interface in the simulator resCode return 1011,registrationID return nil。

get registrationID

call this API to obtain the corresponding RegistrationID. Only if the application successfully registers to JPush The corresponding value is returned only if the server is connected, otherwise an empty string is returned.

Supported versions

Versions supported starting from:1.7.0。

Interface definition

+(NSString *)registrationID

Kind tips:


iOS 9 system, uninstall and reinstall the application,APNs returned devicetoken will change, developers need to obtain the latest version of the device Registration id. please kJPFNetworkDidLoginNotification Called in the implementation method

"RegistrationID"This interface is used to obtain RegistrationID。

Additional notes

pass RegistrationID Push messages and notifications

can pass RegistrationID To push messages and notifications, refer to the documentation Push API v3, when audience The parameters are RegistrationID time can be based on RegistrationID push.

Note: To use this feature, the client App Must be integrated r1.7.0 and above versions JPush iOS SDK

set up Badge

Supported versions

v1.7.4 and subsequent versions

Function description

badge yes iOS A number used to mark the status of an application, appearing in the upper right corner of the application icon. JPush encapsulation badge Function that allows applications to upload badge worth to JPush server, by JPush The background helps manage the push corresponding to each user badge values, simplifying settings push badge operation.

In practical applications, developers can directly badge Values ​​can be increased or decreased without having to maintain user and badge Correspondence between values. When pushing a message, just Set badge +1,Jiguangwill be stored in the server for each user badge The value is automatically +1 and then issued to the user.

Set badge

API setBadge

set up JPush stored in the server badge value

Interface definition

+ (BOOL)setBadge:(int)value
          + (BOOL)setBadge:(int)value

        
This code block is shown in the floating window

Parameter description

  • value Value range: [0,99999]

Still need to call locally UIApplication:setApplicationIconBadgeNumber Displayed on the function settings icon badge value


  • return value
    • exist value Return within the value range of TRUE, otherwise return FALSE

Clear corner mark

API resetBadge

Clear JPush stored in the server badge value, that is [setBadge:0]

Interface definition

+ (void)resetBadge
          + (void)resetBadge

        
This code block is shown in the floating window

local notification

Supported versions

v1.8.0 and subsequent versions,v2.1.9 The version has been updated

Function description

iOS When the device receives a local notification and the user clicks the notification to open the application, the application needs to process it according to the status. AppDelegate Add code to the following two methods in to get local notification content

  • if App status is not running, this function will be called if launchOptions Include UIApplicationLaunchOptionsLocalNotificationKey Indicates that the user clicked on the local notification resulting in app is started to run; if it does not contain the corresponding key value, it means App It is not activated by clicking on the local notification, but may be directly clicked icon to be activated or otherwise.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions; // 本地通知内容获取:NSDictionary *localNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey]
          - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
// 本地通知内容获取:NSDictionary *localNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey]

        
This code block is shown in the floating window
  • if App If the status is running in the foreground or background, then this function will be called and can be passed AppDelegate of applicationState Is it UIApplicationStateActive Determine whether the program is running in the foreground. This situation is handled in this function:
// NS_DEPRECATED_IOS(4_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]") - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification; // 本地通知为 notification
          // NS_DEPRECATED_IOS(4_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]")
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;
// 本地通知为 notification

        
This code block is shown in the floating window
  • exist iOS 10 The above methods will be abandoned by the system and replaced by new UserNotifications Framework in -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:] method substitution. to this end,SDK Encapsulated JPUSHRegisterDelegate protocol, you only need to implement the corresponding protocol method to adapt iOS10 New delegate The method is consistent with the above-mentioned remote push new callback method, that is, the following method:
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^) (NSInteger))completionHandler; // if (![notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { // 本地通知为 notification // } - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)())completionHandler; // if (![response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { // 本地通知为 response.notification // }
          - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^) (NSInteger))completionHandler;
   // if (![notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
   // 本地通知为 notification
   // }

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)())completionHandler;
  // if (![response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  // 本地通知为 response.notification
  // }

        
This code block is shown in the floating window

Register/update local notifications

Supported version

v2.1.9 and subsequent versions

Function description

API For registration or update push (supports iOS 10, and compatible with iOS 10 or below)

Interface definition

+ (void)addNotification:(JPushNotificationRequest *)request;
          + (void)addNotification:(JPushNotificationRequest *)request;

        
This code block is shown in the floating window

Parameter description

  • request [JPushNotificationRequest] Entity type, you can pass in the pushed attributes

Call instructions

request Input the already pushed request.requestIdentifier That is, update the existing push, otherwise register a new push.

code example

- (void)testAddNotification { JPushNotificationContent *content = [[JPushNotificationContent alloc] init]; content.title = @"Test Notifications"; content.subtitle = @"2016"; content.body = @"This is a test code"; content.badge = @1; content.categoryIdentifier = @"Custom Category Name"; // 5s 后提醒 iOS 10 以上支持 JPushNotificationTrigger *trigger1 = [[JPushNotificationTrigger alloc] init]; trigger1.timeInterval = 5; //每小时重复 1 次 iOS 10 以上支持 JPushNotificationTrigger *trigger2 = [[JPushNotificationTrigger alloc] init]; trigger2.timeInterval = 3600; trigger2.repeat = YES; //每周一早上 8:00 提醒,iOS 10 以上支持 NSDateComponents *components = [[NSDateComponents alloc] init]; components.weekday = 2; components.hour = 8; JPushNotificationTrigger *trigger3 = [[JPushNotificationTrigger alloc] init]; trigger3.dateComponents = components; trigger3.repeat = YES; //#import <CoreLocation/CoreLocation.h> //一到某地点提醒,iOS 8 以上支持 CLLocationCoordinate2D cen = CLLocationCoordinate2DMake(37.335400, -122.009201); CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:cen radius:2000.0 identifier:@"jiguang"]; JPushNotificationTrigger *trigger4 = [[JPushNotificationTrigger alloc] init]; trigger4.region = region; //5s 后提醒,iOS 10 以下支持 JPushNotificationTrigger *trigger5 = [[JPushNotificationTrigger alloc] init]; trigger5.fireDate = [NSDate dateWithTimeIntervalSinceNow:5]; JPushNotificationRequest *request = [[JPushNotificationRequest alloc] init]; request.requestIdentifier = @"sampleRequest"; request.content = content; request.trigger = trigger1;//trigger2;//trigger3;//trigger4;//trigger5; request.completionHandler = ^(id result) { NSLog(@"结果返回:%@", result); }; [JPUSHService addNotification:request]; }
          - (void)testAddNotification {
  JPushNotificationContent *content = [[JPushNotificationContent alloc] init];
  content.title = @"Test Notifications";
  content.subtitle = @"2016";
  content.body = @"This is a test code";
  content.badge = @1;
  content.categoryIdentifier = @"Custom Category Name";

  // 5s 后提醒 iOS 10 以上支持
  JPushNotificationTrigger *trigger1 = [[JPushNotificationTrigger alloc] init];
  trigger1.timeInterval = 5;
  //每小时重复 1 次 iOS 10 以上支持
  JPushNotificationTrigger *trigger2 = [[JPushNotificationTrigger alloc] init];
  trigger2.timeInterval = 3600;
  trigger2.repeat = YES;

  //每周一早上 8:00 提醒,iOS 10 以上支持
  NSDateComponents *components = [[NSDateComponents alloc] init];
  components.weekday = 2;
  components.hour = 8;
  JPushNotificationTrigger *trigger3 = [[JPushNotificationTrigger alloc] init];
  trigger3.dateComponents = components;
  trigger3.repeat = YES;

  //#import <CoreLocation/CoreLocation.h>
  //一到某地点提醒,iOS 8 以上支持
  CLLocationCoordinate2D cen = CLLocationCoordinate2DMake(37.335400, -122.009201);
  CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:cen
                                                               radius:2000.0
                                                           identifier:@"jiguang"];
  JPushNotificationTrigger *trigger4 = [[JPushNotificationTrigger alloc] init];
  trigger4.region = region;

  //5s 后提醒,iOS 10 以下支持
  JPushNotificationTrigger *trigger5 = [[JPushNotificationTrigger alloc] init];
  trigger5.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];

  JPushNotificationRequest *request = [[JPushNotificationRequest alloc] init];
  request.requestIdentifier = @"sampleRequest";
  request.content = content;
  request.trigger = trigger1;//trigger2;//trigger3;//trigger4;//trigger5;
  request.completionHandler = ^(id result) {
    NSLog(@"结果返回:%@", result);
  };
  [JPUSHService addNotification:request];
}

        
This code block is shown in the floating window

Remove local notification

Supported version

v2.1.9 and subsequent versions

Function description

API Used to remove push notifications that are pending or have been displayed in the notification center (supports iOS 10, and compatible with iOS 10 or below)

Interface definition

+ (void)removeNotification:(JPushNotificationIdentifier *)identifier;
          + (void)removeNotification:(JPushNotificationIdentifier *)identifier;

        
This code block is shown in the floating window

Parameter description

  • identifier [JPushNotificationIdentifier] Entity type

Call instructions

  • iOS 10 or more identifier set to nil, then remove all push and pending push requests displayed in the notification center. You can also set identifier.delivered and identifier.identifiers to remove push or pending push requests from the notification center.identifier.identifiers If set to nil Or an empty array will remove all push or pending push requests displayed in the notification center under the corresponding flag;iOS Below 10 identifier set to nil, then remove all pushes,identifier.delivered The attribute is invalid. You can also pass identifier.notificationObj Pass in a specific push object to remove this push.

code example

- (void)testRemoveNotification { JPushNotificationIdentifier *identifier = [[JPushNotificationIdentifier alloc] init]; identifier.identifiers = @[@"sampleRequest"]; identifier.delivered = YES; //iOS 10 以上有效,等于 YES 则在通知中心显示的里面移除,等于 NO 则为在待推送的里面移除;iOS 10 以下无效 [JPUSHService removeNotification:identifier]; } - (void)testRemoveAllNotification { [JPUSHService removeNotification:nil]; // iOS 10 以下移除所有推送;iOS 10 以上移除所有在通知中心显示推送和待推送请求 // //iOS 10 以上支持 // JPushNotificationIdentifier *identifier = [[JPushNotificationIdentifier alloc] init]; // identifier.identifiers = nil; // identifier.delivered = YES; //等于 YES 则移除所有在通知中心显示的,等于 NO 则为移除所有待推送的 // [JPUSHService removeNotification:identifier]; }
          - (void)testRemoveNotification {
  JPushNotificationIdentifier *identifier = [[JPushNotificationIdentifier alloc] init];
  identifier.identifiers = @[@"sampleRequest"];
  identifier.delivered = YES;  //iOS 10 以上有效,等于 YES 则在通知中心显示的里面移除,等于 NO 则为在待推送的里面移除;iOS 10 以下无效
  [JPUSHService removeNotification:identifier];
}

- (void)testRemoveAllNotification {
  [JPUSHService removeNotification:nil];  // iOS 10 以下移除所有推送;iOS 10 以上移除所有在通知中心显示推送和待推送请求

//  //iOS 10 以上支持
//  JPushNotificationIdentifier *identifier = [[JPushNotificationIdentifier alloc] init];
//  identifier.identifiers = nil;
//  identifier.delivered = YES;  //等于 YES 则移除所有在通知中心显示的,等于 NO 则为移除所有待推送的
//  [JPUSHService removeNotification:identifier];
}

        
This code block is shown in the floating window

Find local notifications

Supported version

v2.1.9 and subsequent versions

Function description

API Used to find push (supports iOS 10, and compatible with iOS 10 or below)

Interface definition

+ (void)findNotification:(JPushNotificationIdentifier *)identifier;
          + (void)findNotification:(JPushNotificationIdentifier *)identifier;

        
This code block is shown in the floating window

Parameter description

  • identifier [JPushNotificationIdentifier] Entity type

Call instructions

  • iOS 10 or above can be set by setting identifier.delivered and identifier.identifiers to find the corresponding push or pending push request displayed in the notification center,identifier.identifiers If set to nil Or an empty array will return all push or pending push requests displayed in the notification center under the corresponding flag;iOS Below 10 identifier.delivered The attribute is invalid,identifier.identifiers If set nil Or an empty array returns all untriggered pushes.
  • Need to set identifier.findCompletionHandler Callback to get the search results, pass (NSArray *results) returns an array of corresponding objects.

code example

- (void)testFindNotification { JPushNotificationIdentifier *identifier = [[JPushNotificationIdentifier alloc] init]; identifier.identifiers = @[@"sampleRequest"]; identifier.delivered = YES; //iOS 10 以上有效,等于 YES 则在通知中心显示的里面查找,等于 NO 则在待推送的里面查找;iOS10 以下无效 identifier.findCompletionHandler = ^(NSArray *results) { NSLog(@"返回结果为:%@", results); // iOS 10 以下返回 UILocalNotification 对象数组,iOS10 以上根据 delivered 传入值返回 UNNotification 或 UNNotificationRequest 对象数组 }; [JPUSHService findNotification:identifier]; } - (void)testFindAllNotification { JPushNotificationIdentifier *identifier = [[JPushNotificationIdentifier alloc] init]; identifier.identifiers = nil; identifier.delivered = YES; //iOS 10 以上有效,等于 YES 则查找所有在通知中心显示的,等于 NO 则为查找所有待推送的;iOS 10 以下无效 identifier.findCompletionHandler = ^(NSArray *results) { NSLog(@"返回结果为:%@", results); // iOS 10 以下返回 UILocalNotification 对象数组,iOS 10 以上根据 delivered 传入值返回 UNNotification 或 UNNotificationRequest 对象数组 }; [JPUSHService findNotification:identifier]; }
          - (void)testFindNotification {
  JPushNotificationIdentifier *identifier = [[JPushNotificationIdentifier alloc] init];
  identifier.identifiers = @[@"sampleRequest"];
  identifier.delivered = YES;  //iOS 10 以上有效,等于 YES 则在通知中心显示的里面查找,等于 NO 则在待推送的里面查找;iOS10 以下无效
  identifier.findCompletionHandler = ^(NSArray *results) {
  NSLog(@"返回结果为:%@", results); // iOS 10 以下返回 UILocalNotification 对象数组,iOS10 以上根据 delivered 传入值返回 UNNotification 或 UNNotificationRequest 对象数组
};
  [JPUSHService findNotification:identifier];
}

- (void)testFindAllNotification {
  JPushNotificationIdentifier *identifier = [[JPushNotificationIdentifier alloc] init];
  identifier.identifiers = nil;
  identifier.delivered = YES;  //iOS 10 以上有效,等于 YES 则查找所有在通知中心显示的,等于 NO 则为查找所有待推送的;iOS 10 以下无效
  identifier.findCompletionHandler = ^(NSArray *results) {
  NSLog(@"返回结果为:%@", results); // iOS 10 以下返回 UILocalNotification 对象数组,iOS 10 以上根据 delivered 传入值返回 UNNotification 或 UNNotificationRequest 对象数组
};
  [JPUSHService findNotification:identifier];
}

        
This code block is shown in the floating window

Register for local notifications (old)

Function description

API Used to register for local notifications

v2.1.9 will be discarded after the version is released, by AddNotification method to replace it, it is recommended to give up its use as soon as possible.

Interface definition

+ (UILocalNotification *)setLocalNotification:(NSDate *)fireDate alertBody:(NSString *)alertBody badge:(int)badge alertAction:(NSString *)alertAction identifierKey:(NSString *)notificationKey userInfo:(NSDictionary *)userInfo soundName:(NSString *)soundName;
          + (UILocalNotification *)setLocalNotification:(NSDate *)fireDate
                                    alertBody:(NSString *)alertBody
                                        badge:(int)badge
                                  alertAction:(NSString *)alertAction
                                identifierKey:(NSString *)notificationKey
                                     userInfo:(NSDictionary *)userInfo
                                    soundName:(NSString *)soundName;

        
This code block is shown in the floating window

iOS 8 New parameter usage API. No iOS 8 version or no need to use iOS 8 New functions please use the above API

+ (UILocalNotification *)setLocalNotification:(NSDate *)fireDate alertBody:(NSString *)alertBody badge:(int)badge alertAction:(NSString *)alertAction identifierKey:(NSString *)notificationKey userInfo:(NSDictionary *)userInfo soundName:(NSString *)soundName region:(CLRegion *)region regionTriggersOnce:(BOOL)regionTriggersOnce category:(NSString *)category
          
+ (UILocalNotification *)setLocalNotification:(NSDate *)fireDate
                                    alertBody:(NSString *)alertBody
                                        badge:(int)badge
                                  alertAction:(NSString *)alertAction
                                identifierKey:(NSString *)notificationKey
                                     userInfo:(NSDictionary *)userInfo
                                    soundName:(NSString *)soundName
                                       region:(CLRegion *)region
                           regionTriggersOnce:(BOOL)regionTriggersOnce
                                     category:(NSString *)category

        
This code block is shown in the floating window

Parameter description

  • fireDate The time when local push is triggered
  • alertBody Push the content that needs to be displayed locally
  • badge The number of the corner mark. If there is no need to change the corner mark, pass -1
  • alertAction The content displayed by the button of the pop-up box (iOS 8 defaults to "open", other defaults to "start")
  • notificationKey local push identifier
  • userInfo Custom parameters can be used to identify push and add additional information
  • soundName Local notification sound name setting, empty is the default sound
  • region
  • regionTriggersOnce
  • category

Call instructions

fireDate Must be greater than the current time and cannot be empty. The number of registered notifications must be less than 64.

code example

[JPUSHService setLocalNotification:[NSDate dateWithTimeIntervalSinceNow:100] alertBody:@"alert content" badge:1 alertAction:@"buttonText" identifierKey:@"identifierKey" userInfo:nil soundName:nil];
          [JPUSHService setLocalNotification:[NSDate dateWithTimeIntervalSinceNow:100]
                      alertBody:@"alert content"
                          badge:1
                    alertAction:@"buttonText"
                  identifierKey:@"identifierKey"
                       userInfo:nil
                      soundName:nil];

        
This code block is shown in the floating window

Find local notifications (old)

Function description

API for getting custom identifierKey identifier UILocationNotification object

v2.1.9 will be discarded after the version is released, by FindNotification method to replace it, it is recommended to give up its use as soon as possible.

Interface definition

+ (NSArray *)findLocalNotificationWithIdentifier:(NSString *)notificationKey;
          + (NSArray *)findLocalNotificationWithIdentifier:(NSString *)notificationKey;

        
This code block is shown in the floating window

Parameter description

  • notificationKey Get the identifier of the notification object

Call instructions

API Returns an array containing all sums identifierKey matching LocalNotification Object, or an empty array object if not found.

code example

NSArray *LocalNotifications = [JPUSHService findLocalNotificationWithIdentifier:@"identifierKey"];
          NSArray *LocalNotifications = [JPUSHService findLocalNotificationWithIdentifier:@"identifierKey"];

        
This code block is shown in the floating window

Delete local notifications (old)

Function description

API Used to delete the specified LocalNotification object

v2.1.9 will be discarded after the version is released, by RemoveNotification method to replace it, it is recommended to give up its use as soon as possible.

Interface definition

+ (void)deleteLocalNotification:(UILocalNotification *)localNotification;
          + (void)deleteLocalNotification:(UILocalNotification *)localNotification;

        
This code block is shown in the floating window

Parameter description

  • localNotification Deleted local notification object

Call instructions

API parameter localNotification cannot be nil.

code example

[JPUSHService deleteLocalNotification:localNotification];
          [JPUSHService deleteLocalNotification:localNotification];

        
This code block is shown in the floating window

delete specified identifierKey local notifications (old)

Function description

API Used to delete all specified identifierKey Notification object for identifier

v2.1.9 will be discarded after the version is released, by RemoveNotification method to replace it, it is recommended to give up its use as soon as possible.

Interface definition

+ (void)deleteLocalNotificationWithIdentifierKey:(NSString *)notificationKey;
          + (void)deleteLocalNotificationWithIdentifierKey:(NSString *)notificationKey;

        
This code block is shown in the floating window

Parameter description

  • notificationKey The identifier of the deleted notification

Call instructions

API parameter notificationKey cannot be nil.

code example

[JPUSHService deleteLocalNotificationWithIdentifierKey:@"identifierKey"];
          [JPUSHService deleteLocalNotificationWithIdentifierKey:@"identifierKey"];

        
This code block is shown in the floating window

Clear all registered notifications (old)

Function description

API Notification to clear all registrations

v2.1.9 will be discarded after the version is released, by RemoveNotification method to replace it, it is recommended to give up its use as soon as possible.

Interface definition

+ (void)clearAllLocalNotifications;
          + (void)clearAllLocalNotifications;

        
This code block is shown in the floating window

code example

[JPUSHService clearAllLocalNotifications];
          [JPUSHService clearAllLocalNotifications];

        
This code block is shown in the floating window

APP Show notification when in foreground (iOS 10 or less)

Function description

API used in APP When running in the foreground, notifications are still displayed. (The style is UIAlertView)

iOS You can continue to use it below 10,iOS 10 and above in [JPUSHRegisterDelegate jpushNotificationCenter:willPresentNotification:withCompletionHandler:] method called completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert); That’s it, so v2.1.9 It will be abandoned after version 1. It is recommended to give up use as soon as possible.

Interface definition

+ (void)showLocalNotificationAtFront:(UILocalNotification *)notification identifierKey:(NSString *)notificationKey;
          + (void)showLocalNotificationAtFront:(UILocalNotification *)notification
                       identifierKey:(NSString *)notificationKey;

        
This code block is shown in the floating window

Parameter description

  • notification currently triggered UILocalNotification
  • notificationKey Filter notifications that do not need to be displayed in the foreground. only notificationKey The notification of the identifier will be displayed in the foreground. If you need to display everything, pass this parameter nil。

Call instructions

API Must be placed in - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification(AppDelegate.m) under Apple's callback function.

code example

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { [JPUSHService showLocalNotificationAtFront:notification identifierKey:@"identifierKey"]; }
          - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { [JPUSHService showLocalNotificationAtFront:notification identifierKey:@"identifierKey"]; }

        
This code block is shown in the floating window

set up PUSH switch

Supported version

v5.0.0 version start

Function description

controlJiguangmessage status. closure PUSH After that, you will not be able to receiveJiguangNotification push, customized message push,liveActivity Message push is enabled by default.

Interface definition

+ (void)setPushEnable:(BOOL)isEnable completion:(void (^)(NSInteger iResCode))completion;
          + (void)setPushEnable:(BOOL)isEnable completion:(void (^)(NSInteger iResCode))completion;

        
This code block is shown in the floating window

Call example

Call instructions

If you don't want to accept itJiguangNotification push, custom message push and liveActivity For message push, this interface can be called.

code example

[JPUSHService setPushEnable:YES completion:^(NSInteger iResCode) { if (iResCode == 0) { NSLog(@"success"); }else { NSLog(@"fail code:%ld",(long)iResCode); } }];
          [JPUSHService setPushEnable:YES completion:^(NSInteger iResCode) {
    if (iResCode == 0) {
      NSLog(@"success");
    }else {
      NSLog(@"fail code:%ld",(long)iResCode);
    }
  }];

        
This code block is shown in the floating window

get PUSH state

Supported version

v6.0.0 version start

Function description

Get the status of the current push function. You can query whether pushing has been stopped through this interface.

Interface definition

+ (void)getPushStatus:(nullable void (^)(NSInteger iResCode, BOOL isStopped))completion;
          + (void)getPushStatus:(nullable void (^)(NSInteger iResCode, BOOL isStopped))completion;

        
This code block is shown in the floating window

Call example

Call instructions

Call this interface to query the status of the current push function. Result passed completion The callback returns.

Parameter description

  • completion
    • callback block, return the result code and push status
    • iResCode: Result code, 0 indicates success. For other return codes, please refer to the error code definition.
    • isStopped: YES Indicates that push has been stopped, NO indicates that push function is enabled, in iResCode Valid when 0

code example

[JPUSHService getPushStatus:^(NSInteger iResCode, BOOL isStopped) { if (iResCode == 0) { if (isStopped) { NSLog(@"推送已停止"); } else { NSLog(@"推送功能开启"); } } else { NSLog(@"获取推送状态失败,错误码:%ld", (long)iResCode); } }];
          [JPUSHService getPushStatus:^(NSInteger iResCode, BOOL isStopped) {
    if (iResCode == 0) {
        if (isStopped) {
            NSLog(@"推送已停止");
        } else {
            NSLog(@"推送功能开启");
        }
    } else {
        NSLog(@"获取推送状态失败,错误码:%ld", (long)iResCode);
    }
}];

        
This code block is shown in the floating window

Set whether to allow long connections when entering the background

Supported version

v5.9.0 version start

Function description

Set whether to allow long connections when entering the background. The default is NO. Entering the background will close the long connection, and returning to the foreground will reconnect. Please call before initialization function.

Interface definition

+ (void)setBackgroundEnable:(BOOL)isEnable;
          + (void)setBackgroundEnable:(BOOL)isEnable;

        
This code block is shown in the floating window

Call example

Call instructions

isEnable: YES:allow,NO:Not allowed, the default is NO. Entering the background will close the long connection, and returning to the foreground will reconnect.

code example

[JPUSHService setBackgroundEnable:YES];
            [JPUSHService setBackgroundEnable:YES];

        
This code block is shown in the floating window

Log level setting

Supported version

v1.8.0 version start

turn on Debug model

Function description

API used to turn on Debug mode to display more log information

Interface definition

+ (void)setDebugMode;
          + (void)setDebugMode;

        
This code block is shown in the floating window

Call instructions

When you need to know more debugging information, call API turn on Debug model

code example

[JPUSHService setDebugMode];
          [JPUSHService setDebugMode];

        
This code block is shown in the floating window

Turn off log information

Function description

API Used to turn off logging information (except necessary error information)

Interface definition

+ (void)setLogOFF;
          + (void)setLogOFF;

        
This code block is shown in the floating window

Call instructions

When no debugging information is needed, call this API (It is recommended to call this when publishing API, used to shield log information and save performance consumption)

code example

[JPUSHService setLogOFF];
          [JPUSHService setLogOFF];

        
This code block is shown in the floating window

Geographical location statistics

Supported version

v1.8.0 version start

Kind tips:iOS 11 to pop up a pop-up box to obtain the geographical location, it is recommended to info.plist Configure the following 3 key。

NSLocationAlwaysAndWhenInUseUsageDescription

NSLocationAlwaysUsageDescription

NSLocationWhenInUseUsageDescription

Statistics of user geographical information

Function description

API Used to count user geographical information.

Interface definition

+ (void)setLatitude:(double)latitude longitude:(double)longitude;
          + (void)setLatitude:(double)latitude longitude:(double)longitude;

        
This code block is shown in the floating window

Parameter description

  • latitude Geographical location latitude
  • longitude Location longitude

Call instructions

Need to join CoreLocation.framework library, and import <CoreLocation/CoreLocation.h> header file (#import <CoreLocation/CoreLocation.h >)

Longitude and latitude require developers to call Apple’s geographical location information themselves API Get.

code example

[JPUSHService setLatitude:100.0 longitude:100.0];
          [JPUSHService setLatitude:100.0 longitude:100.0];

        
This code block is shown in the floating window

Statistical geographical location information

Function description

API Used to count geographical location information

Interface definition

+ (void)setLocation:(CLLocation *)location;
          + (void)setLocation:(CLLocation *)location;

        
This code block is shown in the floating window

Parameter description

  • location current geographical location CLLocation object

Call instructions

Need to join CoreLocation.framework library, and import <CoreLocation/CoreLocation.h> header file (#import <CoreLocation/CoreLocation.h>)

CLLocation The object requires developers to call Apple’s geographical location information themselves API Get.

code example

Build Phases 中 Link Binary With Libraries 添加 CoreLocation.framework 应用的 plist 增加 NSLocationAlwaysUsageDescription 或 NSLocationWhenInUseUsageDescription 字段,内容为是否允许 alert 的内容 # import <CoreLocation/CoreLocation.h> @interface xxx : UIViewController<CLLocationManagerDelegate> @property(nonatomic, strong) CLLocationManager *currentLoaction; - (void)viewDidLoad { //注册 LocationManager _currentLoaction = [[CLLocationManager alloc] init]; _currentLoaction.delegate = self; # ifdef __IPHONE_8_0 if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) { [_currentLoaction requestAlwaysAuthorization]; } # endif if ([CLLocationManager locationServicesEnabled]) { NSLog(@"您的设备的[设置]-[隐私]-[定位]已开启"); [_currentLoaction startUpdatingLocation]; } else{ NSLog(@"您的设备的[设置]-[隐私]-[定位]尚未开启"); } } # ifdef __IPHONE_6_0 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) { CLLocation *newLocation = [locations lastObject]; float longtitude = newLocation.coordinate.longitude; float latitude = newLocation.coordinate.latitude; [JPUSHService setLocation:newLocation]; //[JPUSHService setLatitude:latitude longitude:longtitude]; [manager stopUpdatingLocation]; } } # endif - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { if ([[UIDevice currentDevice].systemVersion floatValue] < 6.0) { float longtitude = newLocation.coordinate.longitude; float latitude = newLocation.coordinate.latitude; [JPUSHService setLocation:newLocation]; //[JPUSHService setLatitude:latitude longitude:longtitude]; [manager stopUpdatingLocation]; } } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ //获取地理位置错误处理 }
          Build Phases 中 Link Binary With Libraries 添加 CoreLocation.framework
应用的 plist 增加 NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription 字段,内容为是否允许 alert 的内容

# import <CoreLocation/CoreLocation.h>
@interface xxx : UIViewController<CLLocationManagerDelegate>
@property(nonatomic, strong) CLLocationManager *currentLoaction;

- (void)viewDidLoad {
  //注册 LocationManager
  _currentLoaction = [[CLLocationManager alloc] init];
  _currentLoaction.delegate = self;
# ifdef __IPHONE_8_0
  if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
    [_currentLoaction requestAlwaysAuthorization];
  }
# endif
    if ([CLLocationManager locationServicesEnabled]) {
        NSLog(@"您的设备的[设置]-[隐私]-[定位]已开启");
        [_currentLoaction startUpdatingLocation];
    }
    else{
        NSLog(@"您的设备的[设置]-[隐私]-[定位]尚未开启");
  }
}

# ifdef __IPHONE_6_0
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
  if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
    CLLocation *newLocation = [locations lastObject];
    float longtitude = newLocation.coordinate.longitude;
    float latitude = newLocation.coordinate.latitude;
    [JPUSHService setLocation:newLocation];
    //[JPUSHService setLatitude:latitude longitude:longtitude];
    [manager stopUpdatingLocation];
  }
}
# endif

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
  if ([[UIDevice currentDevice].systemVersion floatValue] < 6.0) {
    float longtitude = newLocation.coordinate.longitude;
    float latitude = newLocation.coordinate.latitude;
    [JPUSHService setLocation:newLocation];
    //[JPUSHService setLatitude:latitude longitude:longtitude];
    [manager stopUpdatingLocation];
  }
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{
//获取地理位置错误处理
}

        
This code block is shown in the floating window

Set mobile number

Supported versions

v3.0.8 version start

Function description

Used for SMS supplementary function. After setting the mobile phone number, you can realize the notification method of "the SMS cannot be sent" and improve the push delivery rate.

Implementation method

Interface definition

+ (void)setMobileNumber:(NSString *)mobileNumber completion:(void (^)(NSError *error))completion
          + (void)setMobileNumber:(NSString *)mobileNumber completion:(void (^)(NSError *error))completion

        
This code block is shown in the floating window

Parameter description

  • mobileNumber phone number. It can only start with "+" or a number, and the following content can only contain "-" and numbers, and the length cannot exceed 20. If you pass nil Or an empty string is used to unbind the number.
  • completion Respond to the callback. success rule error is empty, on failure error Contains error codes and error messages. For specific error codes, please see the error code definition.

Call instructions

There is a limit to the frequency of calling this interface.10s Up to 3 times within a period. It is recommended to call this interface after successful login. The result information passes completion Return asynchronously, you can also completion set to nil Result information is not processed.

code example

[JPUSHService setMobileNumber:@"xxx" completion:^(NSError *error) { if (error) { NSLog(@"error:%@", error); } else { // success } }];
          [JPUSHService setMobileNumber:@"xxx" completion:^(NSError *error) {
        if (error) {
          NSLog(@"error:%@", error);
        }
        else {
            // success
        }
      }];

        
This code block is shown in the floating window

Geofencing

Function description

Warm reminder: when using geofences, be sure to configure location permissions first, and then BackgroundModes selected Location updates。

iOS Versions 11 and above must have geographical location Always Use permissions to take effect.

Geofencing (Geo-fencing)yes LBS A new application is to use a virtual fence to enclose a virtual geographical boundary. Your phone can receive automatic notifications and warnings when it enters or leaves a specific geographic area.

Inject callback method when geofence is triggered

call this API Inject callback method when geofence is triggered

Supported versions

Versions supported starting from:3.1.2

Interface definition

+ (void)registerLbsGeofenceDelegate:(id<JPUSHGeofenceDelegate>)delegate withLaunchOptions:(NSDictionary *)launchOptions;
          + (void)registerLbsGeofenceDelegate:(id<JPUSHGeofenceDelegate>)delegate withLaunchOptions:(NSDictionary *)launchOptions;

        
This code block is shown in the floating window

Parameter description

  • delegate
    • acting JPUSHGeofenceDelegate type
    • There are three proxy methods to call back to developers. For specific usage, please refer to the interface description below.
  • launchOptions
    • NSDictionary type application:didFinishlaunchOptions: The dictionary passed in.

Call instructions

exist AppDelegate middle application:didFinishlaunchOptions: call

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [JPUSHService registerLbsGeofenceDelegate:self withLaunchOptions:launchOptions]; }
          - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [JPUSHService registerLbsGeofenceDelegate:self withLaunchOptions:launchOptions];
}

        
This code block is shown in the floating window

Remove geofence

call this API Remove geofence

Supported versions

Versions supported starting from:3.2.1

Interface definition

+ (void)removeGeofenceWithIdentifier:(NSString *)geofenceId;
          + (void)removeGeofenceWithIdentifier:(NSString *)geofenceId;

        
This code block is shown in the floating window

Parameter description

  • geofenceId
    • String type, geofence id. The geofence id is generated when creating a geofence.

Call instructions

[JPUSHService removeGeofenceWithIdentifier:@"geofenceId"];
          [JPUSHService removeGeofenceWithIdentifier:@"geofenceId"];

        
This code block is shown in the floating window

Set the detection period of the 'inside circle' geofence

call this API Set the detection period of the 'inside circle' geofence, which is detected once every 15 minutes by default.

Supported versions

Versions supported starting from:3.6.0

Interface definition

+ (void)setGeofenecePeriodForInside:(NSInteger)seconds;
          + (void)setGeofenecePeriodForInside:(NSInteger)seconds;

        
This code block is shown in the floating window

Parameter description

  • seconds
    • Second

Call instructions

[JPUSHService setGeofenecePeriodForInside:30];
          [JPUSHService setGeofenecePeriodForInside:30];

        
This code block is shown in the floating window

Callback when geofence is triggered

Delegate

Callback when geofence is triggered

Supported versions

Versions supported starting from:3.6.0

Interface definition

  • (void)jpushGeofenceRegion:(NSDictionary _)geofence error:(NSError _)error;

Parameter description

  • geofence
    • Geofencing information
  • error
    • error message

Callback for pulling geofence list

Delegate

Callback for pulling geofence list

Supported versions

Versions supported starting from:3.6.0

Interface definition

- (void)jpushCallbackGeofenceReceived:(NSArray<NSDictionary*> *)geofenceList
          - (void)jpushCallbackGeofenceReceived:(NSArray<NSDictionary*> *)geofenceList

        
This code block is shown in the floating window

Parameter description

  • geofenceList
    • Geofence list

Callback triggered when geofence is entered

Delegate

Callback triggered when the user enters the geofenced area.

Supported versions

Versions supported starting from:3.1.2,3.6.0 The version has expired, the new version can be used directly jpushGeofenceRegion interface

Interface definition

- (void)jpushGeofenceIdentifer:(NSString * _Nonnull)geofenceId didEnterRegion:(NSDictionary * _Nullable)userInfo error:(NSError * _Nullable)error;
          - (void)jpushGeofenceIdentifer:(NSString * _Nonnull)geofenceId didEnterRegion:(NSDictionary * _Nullable)userInfo error:(NSError * _Nullable)error;

        
This code block is shown in the floating window

Parameter description

  • geofenceId
    • geofence unique id
    • NSString string type
  • userInfo
    • NSDictionary type.
    • Display information related to callback when geofence is triggered
  • error
    • error message

Callback triggered when leaving geofence

Delegate

Callback triggered when the user leaves the geofence area.

Supported versions

Versions supported starting from:3.1.2,3.6.0 Version has expired

Interface definition

- (void)jpushGeofenceIdentifer:(NSString * _Nonnull)geofenceId didExitRegion:(NSDictionary * _Nullable)userInfo error:(NSError * _Nullable)error;
          - (void)jpushGeofenceIdentifer:(NSString * _Nonnull)geofenceId didExitRegion:(NSDictionary * _Nullable)userInfo error:(NSError * _Nullable)error;

        
This code block is shown in the floating window

Parameter description

  • geofenceId
    • geofence unique id
    • NSString string type
  • userInfo
    • NSDictionary type.
    • Display information related to callback when geofence is triggered
  • error
    • error message

Set the maximum number of geofence listeners

call this API To set the maximum number of geofence listeners, the default value is 10

Supported versions

Versions supported starting from:3.1.2

Interface definition

+ (void)setGeofeneceMaxCount:(NSInteger)count;
          + (void)setGeofeneceMaxCount:(NSInteger)count;

        
This code block is shown in the floating window

Parameter description

  • count
    • The type requirements are NSInteger type
    • Default value is 10
    • iOS The system requires a maximum of 20, otherwise an error will be reported.

Notification permissions

Check notification authorization status

call this API Detect notification authorization status, in block Return results in

Supported versions

Versions supported starting from:3.2.8

Interface definition

+ (void)requestNotificationAuthorization:(void (^)(JPAuthorizationStatus status))completion;
          + (void)requestNotificationAuthorization:(void (^)(JPAuthorizationStatus status))completion;

        
This code block is shown in the floating window

Parameter description

  • completion
    • Authorization status result returned JPAuthorizationStatus type status value
    • JPAuthorizationStatus For details on type definition, see JPushService.h internal statement

Call instructions

It is recommended to call this interface in a timely manner. Note that when you first start the application to register for remote push, the system will pop up a prompt box. It is best to wait for the user to choose whether to allow it before calling it.

code example

[JPUSHService requestNotificationAuthorization:^(JPAuthorizationStatus status) { // run in main thread, you can custom ui NSLog(@"notification authorization status:%lu", status); // [self alertNotificationAuthorization:status]; }];
          [JPUSHService requestNotificationAuthorization:^(JPAuthorizationStatus status) {
    // run in main thread, you can custom ui
    NSLog(@"notification authorization status:%lu", status);
    // [self alertNotificationAuthorization:status];
 }];

        
This code block is shown in the floating window

Jump to the application settings interface in system settings

call this API Jump to the application settings interface in the system settings. block Return results in

Supported versions

Versions supported starting from:3.2.8

Interface definition

+ (void)openSettingsForNotification:(void (^)(BOOL success))completionHandler NS_AVAILABLE_IOS(8_0);
          + (void)openSettingsForNotification:(void (^)(BOOL success))completionHandler NS_AVAILABLE_IOS(8_0);

        
This code block is shown in the floating window

Parameter description

  • completionHandler
    • The result of successful jump is returned,YES for success, NO for failure

Call instructions

This interface is affected by the system jump interface.iOS Valid for 8 and above,iOS8 The following are not supported.

code example

if(@available(iOS 8.0, *)) { [JPUSHService openSettingsForNotification:^(BOOL success) { NSLog(@"open settings %@", success?@"success":@"failed"); }]; }
          if(@available(iOS 8.0, *)) {
  [JPUSHService openSettingsForNotification:^(BOOL success) {
    NSLog(@"open settings %@", success?@"success":@"failed");
  }];
}

        
This code block is shown in the floating window

Monitor notification authorization status return results

Delegate

implement this API Monitor notification authorization status return results

Supported versions

Versions supported starting from:3.2.8

Interface definition

- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info;
          - (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info;

        
This code block is shown in the floating window

Parameter description

  • status
    • JPAuthorizationStatus Type, authorization notification status, and defined values ​​are detailed in JPushService.h internal statement
  • info
    • NSDictionary Type, more information, reserved parameters, currently available type field, you can call this differently API way

Call instructions

This method is JPUSHRegisterDelegate One of the protocol methods, needs to be set JPUSHRegisterDelegate before it takes effect.

code example

# pragma mark- JPUSHRegisterDelegate - (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info { NSLog(@"receive notification authorization status:%lu, info:%@", status, info); // [self alertNotificationAuthorization:status]; }
          # pragma mark- JPUSHRegisterDelegate

- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info {
  NSLog(@"receive notification authorization status:%lu, info:%@", status, info);
  // [self alertNotificationAuthorization:status];
}

        
This code block is shown in the floating window

Supported versions

Notification Service Extension SDK v1.0.0(Follow JPush iOS SDK 3.0.7 version release) and subsequent versions

Function description

use Notification Service Extension SDK Report push delivery and display status

set up appkey interface

jpushSetAppkey:

set up appkey Interface, must be called in advance

Interface definition

+ (void)jpushSetAppkey:(NSString *)appkey
          + (void)jpushSetAppkey:(NSString *)appkey

        
This code block is shown in the floating window

Parameter description

  • appkey need and main app in JPush SDK of appkey Be consistent

Message display statistics

jpushReceiveNotificationRequest:with:

Message display statistics interface, call this interface to report APNs in the message body JPush Related data

Interface definition

+ (void)jpushReceiveNotificationRequest:(UNNotificationRequest *)request with:(void (^)(void))completion
          + (void)jpushReceiveNotificationRequest:(UNNotificationRequest *)request with:(void (^)(void))completion

        
This code block is shown in the floating window

Parameter description

  • request UNNotificationRequest
  • completion Report callback for message delivery and display. Please execute display in this callback. APNs Wait for operations

Close log

setLogOff

Close log
The default is on, it is recommended to turn it off when publishing to reduce unnecessary IO

Interface definition

+ (void)setLogOff
          + (void)setLogOff

        
This code block is shown in the floating window

Voip Push

Function description

  • exist iOS 8 later introduced a PushKit framed Voip Push can make users’ APP wake up in case of kill APP, and execute the code.

    Warning: in iOS After 13 Apple no longer allowed PushKit Application in non- Voip In the case of telephone, if necessary, use Pushkit You need to access Callkit interface.

Supported version

JPush 3.3.2 and subsequent versions,JCore version must be 2.2.4 and subsequent versions

submit Token

registerVoipToken:

TowardsJiguangServer submission Token

Interface definition

+ (void)registerVoipToken:(NSData *)voipToken;
          + (void)registerVoipToken:(NSData *)voipToken;

        
This code block is shown in the floating window

Parameter description

  • voipToken returned by the system Voiptoken

deal with Voip information

handleVoipNotification:

process received Voip messages, used for statistics Voip Distribution status

Interface definition

+ (void)handleVoipNotification:(NSDictionary *)remoteInfo;
          + (void)handleVoipNotification:(NSDictionary *)remoteInfo;

        
This code block is shown in the floating window

Parameter description

  • remoteInfo Message content

LiveActivity

LiveActivity yes iOS 16.1 Features launched. With the help of ActivityKit Frame, you can launch a live activity to see live updates from your apps on Smart Island and the lock screen. For example, a sports application allows users to initiate live events, where information updates can be seen at a glance during a match (see iOS Release Features Guide )。


In addition, it is also important to note that Apple has LiveActivity There will be a limit on the number of push notifications. If you update frequently LiveActivity The requirement for push notifications needs to be in info.plist Add to file NSSupportsLiveActivitiesFrequentUpdates entry and set its boolean value to YES(For more information please refer to iOS LiveActivity )。


  • fromiOS17.2To start, Apple allows using push to launch aliveactivity, this operation depends onpushToStartToken。 monitorpushToStartTokenUpdates:function getliveactivityofpushToStartTokenchanges and report them toJiguang。

Report liveActivity of PushToStartToken (start uptoken)

Method - registerLiveActivity:pushToStartToken:completion:seq:

call this API Come and report liveActivity of pushToStartToken,exist block results are returned.

Supported versions

Versions supported starting from:5.5.0

Interface definition

+ (void)registerLiveActivity:(NSString *)activityAttributes pushToStartToken:(nullable NSData *)pushToStartToken completion:(nullable JPUSHLiveActivityTokenCompletion)completion seq:(NSInteger)seq;
                  + (void)registerLiveActivity:(NSString *)activityAttributes
            pushToStartToken:(nullable NSData *)pushToStartToken
                  completion:(nullable JPUSHLiveActivityTokenCompletion)completion
                        seq:(NSInteger)seq;

        
This code block is shown in the floating window

Parameter description

  • activityAttributes

    • certainliveActivityDefined attribute type
  • pushToStartToken

    • corresponding to liveactivity of pushToStartToken
  • completion

    *The corresponding status code used for callback return: 0 is success. For other return codes, please refer to the error code definition.seq The session serial number passed in when calling

  • seq

    • The sequence number passed in during the request will be returned unchanged during the callback.
  • LiveActivity pushToStartToken Report callback (Block)

typedef void (^JPUSHLiveActivityTokenCompletion)(NSInteger iResCode, NSString *iLiveActivityId, NSData *pushToken, NSInteger seq);
          
    typedef void (^JPUSHLiveActivityTokenCompletion)(NSInteger iResCode, NSString *iLiveActivityId, NSData *pushToken, NSInteger seq);

        
This code block is shown in the floating window

Report liveActivity of PushToken

Method - registerLiveActivity:pushToken:completion:seq:

call this API Come and report someone liveActivity of PushToken,exist block results are returned.

Supported versions

Versions supported starting from:4.9.0

Interface definition

+ (void)registerLiveActivity:(NSString *)liveActivityId pushToken:(NSData * _Nullable)pushToken completion:(JPUSHLiveActivityTokenCompletion _Nullable )completion seq:(NSInteger)seq;
             + (void)registerLiveActivity:(NSString *)liveActivityId
                   pushToken:(NSData  * _Nullable)pushToken
                  completion:(JPUSHLiveActivityTokenCompletion _Nullable )completion
                         seq:(NSInteger)seq;

        
This code block is shown in the floating window

Parameter description

  • liveActivityId

    • cannot be set nil,liveActivityIdMaximum 64 bytes.
    • identify a certain liveActivity, developer-defined, recommended only. Jiguangthrough this liveActivityId Determine your target audience. The type must be NSString type.
    • liveActivity of pushToken When there are changes, please call this interface to report in time.
    • exist liveActivity When finished, please call this interface to report to SDK,pushToken pass nil。
  • pushToken

    • corresponding to liveactivity of pushToken。
  • completion

    • The corresponding status code used for callback return: 0 is success. For other return codes, please refer to the error code definition.seq The session serial number passed in when calling
  • seq

    • The sequence number passed in during the request will be returned unchanged during the callback.

LiveActivity PushToken Report callback (Block)

typedef void (^JPUSHLiveActivityTokenCompletion)(NSInteger iResCode, NSString *iLiveActivityId, NSData *pushToken, NSInteger seq);
          typedef void (^JPUSHLiveActivityTokenCompletion)(NSInteger iResCode, NSString *iLiveActivityId, NSData *pushToken, NSInteger seq);

        
This code block is shown in the floating window

Supported version

v5.3.0 version start

Interface definition

+ (void)setCollectControl:(JPushCollectControl *)control;
          + (void)setCollectControl:(JPushCollectControl *)control;

        
This code block is shown in the floating window

Call example

Call instructions

Use this interface to controlSDKof data collection. Supported configured data collection items, see JPushCollectControl。

Call example

JPushCollectControl *control = [[JPushCollectControl alloc] init]; control.gps = NO; // 设置为NO ,关闭地理围栏推送。 默认为YES。 [JPUSHService setCollectControl:control];
            JPushCollectControl *control = [[JPushCollectControl alloc] init];
  control.gps = NO; // 设置为NO ,关闭地理围栏推送。 默认为YES。
  [JPUSHService setCollectControl:control];

        
This code block is shown in the floating window

set upuser segmentPush function switch

Supported version

v5.4.0 version start

Interface definition

+ (void)setSmartPushEnable:(BOOL)isEnable;
          + (void)setSmartPushEnable:(BOOL)isEnable;

        
This code block is shown in the floating window

Call example

Call instructions

set upuser segmentPush function switch.YES:Turn on,NO:Off, the default is on.

Call example

[JPUSHService setSmartPushEnable:YES];
            [JPUSHService setSmartPushEnable:YES];

        
This code block is shown in the floating window

Set the App Data Studio extension function switch

Supported version

v5.7.0 version start

Interface definition

+ (void)setDataInsightsEnable:(BOOL)isEnable;
          + (void)setDataInsightsEnable:(BOOL)isEnable;

        
This code block is shown in the floating window

Call example

Call instructions

Set the App Data Studio extension function switch.YES:Turn on,NO:Off, the default is on.

Call example

[JPUSHService setDataInsightsEnable:YES];
            [JPUSHService setDataInsightsEnable:YES];

        
This code block is shown in the floating window

Page statistics (deprecated)

Supported versions

r1.7.0 version starts.

JPush on the series api The functionality has been deprecated.

Function description

Book API Used for statistics of "user-specified page usage time" and reported to the server. Portal presented to developers. Only when the page statistics are correctly integrated can the correct page access path and access depth (PV) data be obtained.

API

Interface definition

+ (void)startLogPageView:(NSString*)pageName; + (void)stopLogPageView:(NSString*)pageName; + (void)beginLogPageView:(NSString*)pageName duration:(int)seconds;
          + (void)startLogPageView:(NSString*)pageName;
+ (void)stopLogPageView:(NSString*)pageName;
+ (void)beginLogPageView:(NSString*)pageName duration:(int)seconds;

        
This code block is shown in the floating window

Parameter description

  • pageName Need custom name for statistics page
  • duration Custom page time

Call instructions

It should be available on all pages that require statistics. viewWillAppear and viewWillDisappear join in startLogPageView and stopLogPageView To count the time spent on the current page.

Or use it directly beginLogPageView to customize the join page and time information.

code example

- (void)viewWillAppear:(BOOL)animated     {         [super viewWillAppear:animated];         [JPUSHService startLogPageView:@"PageOne"];     } - (void)viewWillDisappear:(BOOL)animated     {         [super viewWillDisappear:animated];         [JPUSHService stopLogPageView:@"PageOne"];     }   -(void)trackView    {        [JPUSHService beginLogPageView:@"PageTwo" duration:10];    }
          - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
        [JPUSHService startLogPageView:@"PageOne"];
    }
- (void)viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
        [JPUSHService stopLogPageView:@"PageOne"];
    }  
-(void)trackView
   {
       [JPUSHService beginLogPageView:@"PageTwo" duration:10];
   }

        
This code block is shown in the floating window
Was this document helpful?

Copyright 2011-2026, jiguang.cn, All Rights Reserved. 粤ICP备12056275号-13 Shenzhen Hexun Huagu Information Technology Co., Ltd.

Open in Docs Center