XMPP series (v)---file transfer

Source: Internet
Author: User

The processing of sending and receiving files in XMPP is somewhat different, and receiving file processing is relatively simple and the sending is slightly more complicated.

First, you need to add the file transfer class in the XMPPFramework.h

File transfer//Receive file #import "XMPPIncomingFileTransfer.h"//Send file #import "XMPPOutgoingFileTransfer.h"

1. File Reception

The file receive is passive, so you need to add the File receive module where Xmppstream is initialized:

5, File receive        _xmppincomingfiletransfer = [[Xmppincomingfiletransfer alloc] Initwithdispatchqueue:dispatch_get_ Global_queue (dispatch_queue_priority_background, 0)];        [_xmppincomingfiletransfer Activate:self.xmppStream];        [_xmppincomingfiletransfer adddelegate:self Delegatequeue:dispatch_get_main_queue ()];        Set to automatically receive files, of course, you can also pop a alertview in the proxy method to let the user choose whether to receive        [_xmppincomingfiletransfer Setautoacceptfiletransfers:yes];
Add agent for File receiveXmppincomingfiletransferdelegate,

Because the file receives XMPP does not generate the corresponding message for us, you must implement the proxy method for file reception:

#pragma mark ===== File receive =======/** Do you agree to send me a file */-(void) Xmppincomingfiletransfer: (Xmppincomingfiletransfer *) sender    Didreceivesioffer: (XMPPIQ *) offer{NSLog (@ "%s", __function__); Pop up a check box to receive it//[Self.xmppincomingfiletransfer Acceptsioffer:offer];} -(void) Xmppincomingfiletransfer: (Xmppincomingfiletransfer *) sender Didsucceedwithdata: (NSData *) data named: (    NSString *) name{Xmppjid *jid = [Sender.senderjid copy];    NSLog (@ "%s", __function__);    In this method, we pass the file with the foreign transfer//So our message Synchronizer does not help us to automatically generate a message, so we need to manually store the message//according to the file suffix name, determine whether we can handle the file, if not processing it is displayed directly.    Picture audio (. Wav,.mp3,.mp4) NSString *extension = [name pathextension]; if (![    @ "wav" isequaltostring:extension]) {return;    }//Create a Xmppmessage object, the message must have from xmppmessage *message = [xmppmessage messagewithtype:@ "chat" To:jid]; <span class= "S1" style= "font-family: ' Comic Sans MS ';" > To </span><span class= "S2" style= "font-family: ' Comic Sans MS ';" >message</span><span class="S1" style= "font-family: ' Comic Sans MS ';" > Add </span><span class= "s2" style= "font-family: ' Comic Sans MS ';"    >from</span> [Message addattributewithname:@ "from" stringValue:sender.senderJID.bare];        [Message addsubject:@ "audio"]; Save data NSString *path = [Nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES) lastObject    ];    Path = [path Stringbyappendingpathcomponent:[xmppstream generateuuid]];    Path = [path stringbyappendingpathextension:@ "wav"];        [Data Writetofile:path Atomically:yes];        [Message addBody:path.lastPathComponent]; [Self.xmppmessagearchivingcoredatastorage archivemessage:message outgoing:no xmppStream:self.xmppStream];}
When[Self.xmppmessagearchivingcoredatastorage archivemessage:message outgoing:no XmppStream:self.xmppStream]; A notification is sent after execution, and the corresponding history message is updated.

2. File sending

XMPP's ability to send files depends on the other client, and after Xmppstream establishes a connection, it asks the client's characteristics and then, based on the characteristics returned, determines whether the other person can receive a file of a certain type.

The features that XMPP supports are:

<query xmlns= "Http://jabber.org/protocol/disco#info" >*     <identity category= "client" type= "Phone"/> *       <feature var= "http://jabber.org/protocol/si"/>*       <feature var= "http://jabber.org/protocol/si/ Profile/file-transfer "/>*       <feature var=" Http://jabber.org/protocol/bytestreams "/>*       <feature Var= "Http://jabber.org/protocol/ibb"/>*   </query>
First, add a property to the chat controller and addxmppoutgoingfiletransferdelegate

@property (nonatomic, strong) Xmppoutgoingfiletransfer *xmppoutgoingfiletransfer;
Record an audio here and send it.

Add a Recording button when the button is pressed to start recording Startrecord:, when the button is lifted, send the recording Sendrecord:, underline the button area to cancel the recording Cancelrecord:,

-(Ibaction) Startrecord: (ID) Sender {nsstring *path = [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, NSUse    Rdomainmask, YES) lastobject];    Path = [path Stringbyappendingpathcomponent:[xmppstream generateuuid]];        Path = [path stringbyappendingpathextension:@ "wav"];    Nsurl *url = [Nsurl Fileurlwithpath:path];    _recorder = [[Avaudiorecorder alloc] Initwithurl:url settings:nil Error:nil];    [_recorder Preparetorecord]; [_recorder record];}    -(Ibaction) Sendrecord: (ID) Sender {[_recorder stop];    Nsarray *resources = [[Jkxmpptool sharedinstance].xmpprostermemorystorage Sortedresources:yes]; For (Xmppresourcememorystorageobject *object in resources) {if ([Object.jid.bare isEqualToString:self.chatJID.bare            ] {NSData *data = [[[[NSData alloc] initwithcontentsofurl:_recorder.url] copy];            Nserror *err; [Self.xmppoutgoingfiletransfer senddata:data named:_recorder.url.lastpathcomponent ToRecipient:object.jid Description:nilerror:&err];            if (err) {NSLog (@ "%@", err);        } break; }} _recorder = nil;}    -(Ibaction) Cancelrecord: (ID) Sender {[_recorder stop];    [[Nsfilemanager Defaultmanager] Removeitematurl:_recorder.url Error:nil]; _recorder = nil;}
When the recording is sent, if the sending fails, it will return in error, failure information, I use Spark to do the receiving client, I returned the other side does not support the failure information.
In addition, sending a file requires you to manually create and save a message, and you can create and save the message in the agent method that sent it successfully.

-(void) Xmppoutgoingfiletransferdidsucceed: (Xmppoutgoingfiletransfer *) sender{    NSLog (@ " Xmppoutgoingfiletransferdidsucceed ");        Xmppmessage *message = [xmppmessage messagewithtype:@ "chat" To:self.chatJID];        The sender of this file is added to the From    [message addattributewithname:@ ' from ' Stringvalue:[jkxmpptool sharedinstance] of the message. XmppStream.myJID.bare];    [Message addsubject:@ "audio"];        NSString *path =  [Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) lastObject];    Path = [path stringByAppendingPathComponent:sender.outgoingFileName];        [Message addBody:path.lastPathComponent];        [[Jkxmpptool sharedinstance].xmppmessagearchivingcoredatastorage archivemessage:message Outgoing:NO xmppStream:[ Jkxmpptool Sharedinstance].xmppstream];}

Demo Address: Https://github.com/Joker-King/ChatDemo

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

XMPP series (v)---file transfer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.