如何在同一个ios设备中将数据从一个应用程序传输到另一个应用程序?

时间:2015-02-19 18:47:10

标签: ios objective-c

我想将一些数据从应用发送到另一个应用。我该怎么做?我不能使用iCloud。我看一下文档提供者,但我不明白如何使用它。

http://adcdownload.apple.com//wwdc_2014/wwdc_2014_sample_code/newboxanintroductiontoiclouddocumentenhancementsinios8.0.zip

我下载了这个例子,但是当我运行它时,它需要iCloud。我没有开发者计划。

任何想法,我该如何解决? (对不起我的英文)

2 个答案:

答案 0 :(得分:1)

有一个UIDocumentInteractionController在iOS上共享文件的示例。 iOS旨在防止应用直接共享数据。因此,Apple提供的UIDocumentInteractionController是您应该用来模仿类似直接共享的东西。

-(void)shareOnInstagram:(UIImage*)image {

    NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/image.igo"];
    [[NSFileManager defaultManager] removeItemAtPath:jpgPath error:nil];
    [UIImageJPEGRepresentation(image, 0.6) writeToFile:jpgPath atomically:YES];

    NSURL *igImageHookFile = [NSURL fileURLWithPath:jpgPath];
    self.dic = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
    self.dic.UTI = @"com.instagram.exclusivegram";
    [self.dic presentOpenInMenuFromRect:CGRectMake(0, 0, 320, [UIScreen mainScreen].bounds.size.height) inView:self.view animated:YES];
}

- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
    UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
    interactionController.delegate = interactionDelegate;
    return interactionController;
}

请参阅https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDocumentInteractionController_class/

答案 1 :(得分:0)

几个月前我完成了它。这里有我使用套接字的解决方案:

  

服务器部分

DataProviderServer.h

#import <Foundation/Foundation.h>

@interface DataProviderServer : NSObject

- (void) startServer;

@end

DataProviderServer.m

#include <CoreFoundation/CoreFoundation.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <netdb.h>
#import  "DataProviderServer.h"

#define SERVER_PORT 8080

@implementation DataProviderServer

- (void) startServer
{
    CFSocketContext CTX = { 0, NULL, NULL, NULL, NULL };
    CFSocketRef TCPServer = CFSocketCreate(
                                           kCFAllocatorDefault,
                                           PF_INET,
                                           SOCK_STREAM,
                                           IPPROTO_TCP,
                                           kCFSocketAcceptCallBack, (CFSocketCallBack)AcceptCallBack, &CTX);
    if (TCPServer == NULL)
    {
        NSLog(@"TCPServer = null");
        return ;
    }
    int optval = 1;
    setsockopt(CFSocketGetNative(TCPServer), SOL_SOCKET, SO_REUSEADDR,
               (void *)&optval, sizeof(optval));

    struct sockaddr_in sin;

    memset(&sin, 0, sizeof(sin));
    sin.sin_len = sizeof(sin);
    sin.sin_family = AF_INET;
    sin.sin_port = htons(SERVER_PORT);
    sin.sin_addr.s_addr= htonl(INADDR_ANY);

    NSData *address = [ NSData dataWithBytes: &sin length: sizeof(sin) ];
    if (CFSocketSetAddress(TCPServer, (CFDataRef) address) != kCFSocketSuccess)
    {
        NSLog(@"CFSocketSetAddress() failed");
        CFRelease(TCPServer);
        return ;
    }

    CFRunLoopSourceRef sourceRef =
    CFSocketCreateRunLoopSource(kCFAllocatorDefault, TCPServer, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), sourceRef, kCFRunLoopCommonModes);
    CFRelease(sourceRef);

    NSLog(@"Socket listening on port %d", SERVER_PORT);

    CFRunLoopRun();
}

void AcceptCallBack(
                    CFSocketRef socket,
                    CFSocketCallBackType type,
                    CFDataRef address,
                    const void *data,
                    void *info)
{
    CFReadStreamRef readStream = NULL;
    CFWriteStreamRef writeStream = NULL;
    CFIndex bytes;
    UInt8 buffer[128];
    UInt8 send_len = 0;

    CFSocketNativeHandle sock = *(CFSocketNativeHandle *) data;

    char * sendNumber = (char *)malloc(sizeof(char) * 128);

    CFStreamCreatePairWithSocket(kCFAllocatorDefault, sock,
                                 &readStream, &writeStream);

    if (!readStream || !writeStream)
    {
        close(sock);
        NSLog(@"CFStreamCreatePairWithSocket() failed");
        free(sendNumber);
        return;
    }

    CFReadStreamOpen(readStream);
    CFWriteStreamOpen(writeStream);

    unsigned count = 1;
    while (YES)
    {
        count++;
        sprintf(sendNumber, "%d", count);
        strcat(sendNumber, "\r\n");
        send_len = 0;
        memset(buffer, 0, sizeof(buffer));
        while (send_len < (strlen(sendNumber+1)))
        {
            if (CFWriteStreamCanAcceptBytes(writeStream))
            {
                bytes = CFWriteStreamWrite(writeStream,
                                           (unsigned char *) sendNumber + send_len,
                                           (strlen((sendNumber)+1) - send_len) );
                if (bytes < 0)
                {
                    NSLog(@"CFWriteStreamWrite() failed");
                    close(sock);
                    free(sendNumber);
                    return;
                }
                send_len += bytes;
            }
        }
        sleep(1);
    }
    return;
}
@end

如何使用

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
                   ^{
                       self.server = [[DataProviderServer alloc] init];
                       [self.server startServer];
                   });
  

客户端部分

DataRequesterClient.h

#import <Foundation/Foundation.h>

@interface DataRequesterClient : NSObject

- (void) sendMessage;
- (id) initWithDelegate: (id) delegate;

@end

DataRequesterClient.m

#include <CoreFoundation/CoreFoundation.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
#import  "DataRequesterClientDelegate.h"
#import  "DataRequesterClient.h"

#define PORT 8080

static id <DataRequesterClientDelegate> delegateForSend; //TODO: global variable fixme

@interface DataRequesterClient ()

@end

@implementation DataRequesterClient

- (id) initWithDelegate: (id) delegate
{
    self = [super init];
    if(self)
    {
        delegateForSend = delegate;
    }
    return self;
}
- (void) sendMessage
{
    CFSocketContext CTX = { 0, NULL, NULL, NULL, NULL };

    CFSocketRef TCPClient = CFSocketCreate(NULL, PF_INET, SOCK_STREAM, IPPROTO_TCP,
                               kCFSocketConnectCallBack, (CFSocketCallBack)ConnectCallBack, &CTX);
    if (TCPClient == NULL)
        return ;

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_len = sizeof(addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    CFDataRef connectAddr = CFDataCreate(NULL, (unsigned char *)&addr, sizeof(addr));

    CFSocketConnectToAddress(TCPClient, connectAddr, -1);
    CFRelease(connectAddr);
    CFRunLoopSourceRef sourceRef = CFSocketCreateRunLoopSource(kCFAllocatorDefault, TCPClient, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), sourceRef, kCFRunLoopCommonModes);
    CFRelease(sourceRef);

    CFRunLoopRun();
}

void ConnectCallBack(
                     CFSocketRef socket,
                     CFSocketCallBackType type,
                     CFDataRef address,
                     const void *data,
                     void * info )
{
    UInt8 buffer[128];
    CFSocketNativeHandle sock = CFSocketGetNative(socket);
    while (YES)
    {
        memset(buffer, 0, sizeof(buffer));
        recv(sock, buffer, sizeof(buffer), 0);
        NSLog(@"Recieved:%s", buffer);
        [delegateForSend didChangeString: [NSString stringWithUTF8String: (char *)buffer]];
    }
}
@end

如何使用

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.client = [[DataRequesterClient alloc] initWithDelegate: self];
        [self.client sendMessage];
    });