Browse SDKs · iOS
Platform
SDKsiOSEnterprise

Load message context

Retrieve messages before and after a specified message with OpenIM iOS SDK.

Copy

When navigating from global search results, jump-to-quote interactions, or specific message alerts, invoke fetchSurroundingMessages:onSuccess:onFailure: on OIMManager to load historical messages surrounding a target anchor message:

Parameters

ParameterTypeRequiredDescription
reqOIMFetchSurroundingMessagesReq *YesRequest configuration parameters object.

Properties of OIMFetchSurroundingMessagesReq

ParameterTypeRequiredDescription
startMessageOIMMessageInfo *YesReference anchor message model.
beforeNSIntegerYesNumber of messages to retrieve before (earlier than) the anchor.
afterNSIntegerYesNumber of messages to retrieve after (newer than) the anchor.
viewTypeOIMFetchSurroundingHistoryViewTypeYesContext view query type (e.g. OIMFetchSurroundingHistoryViewTypeSearch for search jumps).

Code example

OIMFetchSurroundingMessagesReq *request = [OIMFetchSurroundingMessagesReq new];
request.startMessage = locatedMessage;
request.viewType = OIMFetchSurroundingHistoryViewTypeSearch;
request.before = 20;
request.after = 20;

[[OIMManager manager] fetchSurroundingMessages:request
    onSuccess:^(NSArray<OIMMessageInfo *> * _Nullable messages) {
        // Refresh context view with messages sorted in chronological order
        [self replaceContext:messages ?: @[]];
    }
    onFailure:^(NSInteger code, NSString * _Nullable msg) {
        // Handle context fetch failure
    }];

Return value

The onSuccess callback delivers an array of OIMMessageInfo models sorted in chronological order (NSArray<OIMMessageInfo *> *).

State changes after the call

  1. Context array boundaries: The actual number of returned messages may be smaller than before + after + 1 if the anchor is near the start or end of the conversation history. Deduplicate items using clientMsgID scoped to conversationID rather than relying on fixed index positions.
  2. Obtaining anchor models: If you only have a message ID rather than a complete model, locate the anchor object first using Find messages by ID.