File Sharing API for Objective-C SDK
You can upload and share files up to 5 MB on PubNub. Common uses include sharing images in chat apps and documents in healthcare.
When a file is uploaded on a channel, it's stored and managed using a storage service, and associated with your key. Subscribers to that channel receive a file event which contains a file ID, filename, and optional description.
Send file
Upload the file to a specified channel.
This method covers the entire process of sending a file, including preparation, uploading the file to a cloud storage service, and post-uploading messaging on a channel.
For the last messaging step, sendFileWithRequest internally calls the publishFileMessageWithRequest method to publish a message on the channel.
The published message contains metadata about the file, such as the file identifier and name, enabling others on the channel to find out about the file and access it.
For details on the method that publishes the file message, see Publish file message.
Method(s)
1- (void)sendFileWithRequest:(PNSendFileRequest *)request
2 completion:(nullable PNSendFileCompletionBlock)block;
| Parameter | Description |
|---|---|
request *Type: PNSendFileRequest | Send file request with all information about file and where it should be uploaded. |
blockType: PNSendFileCompletionBlock | Send file file request completion block. |
PNSendFileRequest
| Parameter | Description |
|---|---|
fileMessageMetadataType: NSDictionary Default: n/a | NSDictionary with values to be used by PubNub service to filter file messages. |
fileMessageTTLType: NSUInteger Default: 0 | How long the message should be stored in the channel's storage. Set to 0 (zero) to store the message according to the key's retention policy. |
fileMessageStoreType: BOOL Default: YES | Whether to store published file messages in the channel's history. |
messageType: id Default: n/a | Message to be sent along with the file to the specified channel. |
filename *Type: NSString Default: n/a | Name to be used to store uploaded data. This is set by default only if the request is created with requestWithChannel:fileURL:. |
Deprecated parameter
The cipherKey parameter in this method is deprecated. We recommend that you configure the crypto module on your PubNub instance instead.
If you pass cipherKey as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
Sample code
1#import <Foundation/Foundation.h>
2#import <PubNub/PubNub.h>
3
4// Basic configuration
5PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"demo"
6 subscribeKey:@"demo"
7 userID:@"fileUser"];
8
9// Optional: Configure encryption for files
10config.cryptoModule = [PNCryptoModule AESCBCCryptoModuleWithCipherKey:@"enigma"
11 randomInitializationVector:YES];
12
13// Create a PubNub client instance
14PubNub *client = [PubNub clientWithConfiguration:config];
15
show all 74 linesResponse
1@interface PNSendFileData : PNServiceData
2
3// Unique identifier assigned to the file during upload
4@property (nonatomic, nullable, readonly, strong) NSString *fileIdentifier;
5
6// Time at which the file information message was published.
7@property (nonatomic, nullable, readonly, strong) NSNumber *timetoken;
8
9// Name under which the uploaded file is stored
10@property (nonatomic, nullable, readonly, strong) NSString *fileName;
11
12/**
13 * Whether the file uploaded or not.
14 *
15 * This property should be used during error handling to identify whether the
show all 28 linesOther examples
Upload binary data
1NSData *data = [[NSUUID UUID].UUIDString dataUsingEncoding:NSUTF8StringEncoding];
2PNSendFileRequest *request = [PNSendFileRequest requestWithChannel:@"channel"
3 fileName:@"cat_picture.jpg"
4 data:data];
5
6[self.client sendFileWithRequest:request completion:^(PNSendFileStatus *status) {
7 if (!status.isError) {
8 /**
9 * File upload successfully completed.
10 * Uploaded file information available here:
11 * status.data.fileIdentifier - unique file identifier
12 * status.data.fileName - name which has been used to store file
13 */
14 } else {
15 /**
show all 23 linesUpload using stream
1NSInputStream *stream = ...;
2NSUInteger streamSize = /* size of data in stream */;
3PNSendFileRequest *request = [PNSendFileRequest requestWithChannel:@"channel"
4 fileName:@"image.png"
5 stream:stream
6 size:streamSize];
7
8[self.client sendFileWithRequest:request completion:^(PNSendFileStatus *status) {
9 if (!status.isError) {
10 /**
11 * File upload successfully completed.
12 * Uploaded file information available here:
13 * status.data.fileIdentifier - unique file identifier
14 * status.data.fileName - name which has been used to store file
15 */
show all 25 linesReturns
Same as from basic usage.
List channel files
Retrieve list of files uploaded to Channel.
Method(s)
1- (void)listFilesWithRequest:(PNListFilesRequest *)request
2 completion:(PNListFilesCompletionBlock)block;
| Parameter | Description |
|---|---|
request *Type: PNListFilesRequest | List files request with all information which should be used to fetch channel's files list. |
block *Type: PNListFilesCompletionBlock | List files request completion block. |
PNListFilesRequest
| Parameter | Description |
|---|---|
nextType: NSString Default: n/a | Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off. |
limitType: NSUInteger Default: 100 | Number of files to return in response. |
Sample code
1PNListFilesRequest *request = [PNListFilesRequest requestWithChannel:@"channel"];
2request.limit = 20;
3request.next = ...;
4
5[self.client listFilesWithRequest:request
6 completion:^(PNListFilesResult *result, PNErrorStatus *status) {
7 if (!status.isError) {
8 /**
9 * Uploaded files list successfully fetched.
10 * result.data.files - List of uploaded files (information).
11 * result.data.next - Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
12 * result.data.count - Total number of files uploaded to channel.
13 */
14 } else {
15 /**
show all 22 linesResponse
1@interface PNListFilesData : PNServiceData
2
3// List of channel files.
4@property (nonatomic, nullable, readonly, strong) NSArray<PNFile *> *files;
5
6// Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
7@property (nonatomic, nullable, readonly, strong) NSString *next;
8
9// How many files has been returned.
10@property (nonatomic, readonly, assign) NSUInteger count;
11
12@end
13
14@interface PNListFilesResult : PNResult
15
show all 19 linesGet file URL
Generate a URL to download a file from the target channel.
Method(s)
1- (nullable NSURL *)downloadURLForFileWithName:(NSString *)name
2 identifier:(NSString *)identifier
3 inChannel:(NSString *)channel;
| Parameter | Description |
|---|---|
name *Type: NSString | Name under which uploaded file is stored for channel. |
identifier *Type: NSString | Unique file identifier which has been assigned during file upload. |
channel *Type: NSString | Name of channel within which file with name has been uploaded. |
Sample code
1NSURL *url = [self.client downloadURLForFileWithName:@"user_profile.png"
2 identifier:@"<file-identifier>"
3 inChannel:@"lobby"];
Returns
URL which can be used to download remote file with specified name and identifier.
Download file
Download a file from the specified channel.
Method(s)
1- (void)downloadFileWithRequest:(PNDownloadFileRequest *)request
2 completion:(PNDownloadFileCompletionBlock)block;
| Parameter | Description |
|---|---|
request *Type: PNDownloadFileRequest | Download file request with information about file which should be downloaded. |
block *Type: PNDownloadFileCompletionBlock | Download file request completion block. |
PNDownloadFileRequest
| Parameter | Description |
|---|---|
targetURLType: NSURL Default: Temporary location | URL where the downloaded file should be stored locally. A file downloaded to a temporary location is removed after the completion block returns. |
Deprecated parameter
The cipherKey parameter in this method is deprecated. We recommend that you configure the crypto module on your PubNub instance instead.
If you pass cipherKey as an argument, it overrides the crypto module configuration and the legacy encryption with 128-bit cipher key entropy is used.
Sample code
1PNDownloadFileRequest *request = [PNDownloadFileRequest requestWithChannel:@"lobby"
2 identifier:@"<file-identifier>"
3 name:@"user_profile.png"];
4request.targetURL = ...;
5
6[self.client downloadFileWithRequest:request
7 completion:^(PNDownloadFileResult *result, PNErrorStatus *status) {
8
9 if (!status.isError) {
10 /**
11 * File successfully has been downloaded.
12 * status.data.location - location where downloaded file can be found
13 * status.data.temporary - whether file has been downloaded to temporary storage and
14 * will be removed on completion block return.
15 */
show all 24 linesResponse
1@interface PNDownloadFileData : PNServiceData
2
3/**
4 * Whether file is temporary or not.
5 *
6 * Temporary file will be removed as soon as completion block will exit. Make sure
7 * to move temporary files (w/o scheduling task on secondary thread) to persistent
8 * location.
9 */
10@property (nonatomic, readonly, assign, getter = isTemporary) BOOL temporary;
11
12// Location where downloaded file can be found.
13@property (nonatomic, readonly, nullable, readonly, strong) NSURL *location;
14
15@end
show all 22 linesDelete file
Delete a file from the specified channel.
Method(s)
1- (void)deleteFileWithRequest:(PNDeleteFileRequest *)request
2 completion:(nullable PNDeleteFileCompletionBlock)block;
| Parameter | Description |
|---|---|
request *Type: PNDeleteFileRequest | Delete file request with all information about file for removal. |
blockType: PNDeleteFileCompletionBlock | Delete file request completion block. |
Sample code
1PNDeleteFileRequest *request = [PNDeleteFileRequest requestWithChannel:@"channel"
2 identifier:@"<file-identifier>"
3 name:@"greetings.txt"];
4
5[self.client deleteFileWithRequest:request completion:^(PNAcknowledgmentStatus *status) {
6 if (!status.isError) {
7 // File successfully has been deleted.
8 } else {
9 /**
10 * Handle file delete error. Check 'category' property to find out possible issue
11 * because of which request did fail.
12 *
13 * Request can be resent using: [status retry]
14 */
15 }
show all 16 linesResponse
1@interface PNErrorData : PNServiceData
2
3// Stringified error information.
4@property (nonatomic, readonly, strong) NSString *information;
5
6@end
7
8@interface PNAcknowledgmentStatus : PNErrorStatus
9
10// Whether status object represent error or not.
11@property (nonatomic, readonly, assign, getter = isError) BOOL error;
12
13// Additional information related to error status object.
14@property (nonatomic, readonly, strong) PNErrorData *errorData;
15
show all 16 linesPublish file message
Publish the uploaded file message to a specified channel.
This method is called internally by sendFileWithRequest as part of the file-sending process to publish the message with the file (already uploaded in a storage service) on a channel.
This message includes the file's unique identifier and name elements, which are needed to construct download links and inform channel subscribers that the file is available for download.
You can call this method when sendFileWithRequest fails and returns the status.operation === PNPublishFileMessageOperation error.
In that case, you can use the data from the status object to try again and use publishFileMessageWithRequest to manually resend a file message to a channel without repeating the upload step.
Method(s)
1- (void)publishFileMessageWithRequest:(PNPublishFileMessageRequest *)request
2 completion:(nullable PNPublishCompletionBlock)block;
| Parameter | Description |
|---|---|
request * | File message publish request with all information about uploaded file. |
blockType: PNPublishCompletionBlock | File message publish request completion block. |
PNPublishFileMessageRequest
| Property | Description |
|---|---|
identifierType: NSString* | Unique identifier provided during file upload. |
filenameType: NSString* | Name with which uploaded data has been stored. |
customMessageTypeType: NSString* | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-. Examples: text, action, poll. |
You can also set any parameters from the PNBasePublishRequest request:
| Property | Description |
|---|---|
arbitraryQueryParametersType: NSDictionary* | Arbitrary percent-encoded query parameters which should be sent along with the original API call. |
preparedMetadataType: NSString* | Serialized NSDictionary with values used by PubNub service to filter messages. |
replicateType: BOOL | Whether the message should be replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel. |
storeType: BOOL | Whether published data should be stored and available with the history API or not. |
metadataType: NSDictionary* | NSDictionary with values used by PubNub service to filter messages. |
channelType: NSString* | Name of channel to which the message should be published. |
messageType: id | Message to be published. The object is serialized into JSON (supports NSString, NSNumber, NSArray, NSDictionary). If you configured a crypto module, the message is encrypted. |
ttlType: NSUInteger | Duration for which the message should be stored in the channel's storage. Passing \b 0 will store the message according to retention policy. |
retriedType: BOOL | Indicates whether the request is repeatedly sent to retry after a recent failure. |
Sample code
1PNPublishFileMessageRequest *request = [PNPublishFileMessageRequest requestWithChannel:@"channel"
2 fileIdentifier:@"fileIdentifier"
3 name:@"fileName"];
4request.customMessageType = @"file-message";
5
6[self.client publishFileMessageWithRequest:request completion:^(PNPublishStatus *status) {
7 if (!status.isError) {
8 // File message successfully published.
9 } else {
10 // Handle file message publish error. Check 'category' property to find out possible
11 // issue because of which request did fail.
12 //
13 // Request can be resent using: [status retry];
14 }
15}];
Response
1@interface PNPublishData : PNServiceData
2
3/**
4 * Service-provided time stamp at which message has been pushed to remote
5 * data object live feed.
6 */
7@property (nonatomic, readonly, strong) NSNumber *timetoken;
8
9// Service-provide information about service response message.
10@property (nonatomic, readonly, strong) NSString *information;
11
12@end
13
14@interface PNPublishStatus : PNAcknowledgmentStatus
15
show all 19 lines