2014-03-28 51 views
1

專家:目標c - 將圖像文件寫入IP地址

我一直在研究如何通過IP地址將圖像文件寫入另一臺計算機。我是否真的需要創建套接字,設置代理,安排運行循環,檢查可用空間以及所有這些情況?真?我不能只使用IP地址和默認端口將文件保存到URL?

我在問這個問題,因爲我自己並沒有取得很大的進展,而且我知道我打的一分鐘後發佈您的問題我會找到一些有用的信息。但如果沒有發生,請回復。任何幫助表示讚賞。

這是我的代碼,我想我是在錯誤的軌道上:

#import "TESTtcpController.h" 

@interface TESTtcpController() 

@property (nonatomic, strong)NSInputStream *inputStream; 
@property (nonatomic, strong)NSOutputStream *outputStream; 

//void CFStreamCreatePairWithSocketToHost (
//           CFAllocatorRef alloc, 
//           CFStringRef host, 
//           UInt32 port, 
//           CFReadStreamRef *readStream, 
//           CFWriteStreamRef *writeStream 
//          ); 

@end 

@implementation TESTtcpController 

+ (void)sendFile:(UIImage *)image 
{ 
    UInt32 port = 80; 
    NSString *ipAddress = @"10.10.10.10"; 
    TESTtcpController *tcpController = [[TESTtcpController alloc] init]; 
    [tcpController connect:port ipAddress:ipAddress]; 
    [tcpController postFile:image]; 
    [tcpController disconnect]; 
    tcpController = nil; 
} 

-(void)connect:(UInt32)port ipAddress:(NSString *)ipAddress 
{ 
    CFReadStreamRef readStream; 
    CFWriteStreamRef writeStream; 
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)ipAddress, port, &readStream, &writeStream); 
    self.inputStream = (__bridge NSInputStream *)readStream; 
    self.outputStream = (__bridge NSOutputStream *)writeStream; 
    [self.inputStream setDelegate:self]; 
    [self.outputStream setDelegate:self]; 
    [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
    [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
    [self.inputStream open]; 
    [self.outputStream open]; 
    NSLog(@"input stream id %@", self.inputStream); 

    /* Store a reference to the input and output streams so that 
    they don't go away.... */ 

} 

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

} 

- (void)dataSending:(NSString*)data { 
    if(self.outputStream) { 
     if(![self.outputStream hasSpaceAvailable]) 
      return; 
     NSData *_data=[data dataUsingEncoding:NSUTF8StringEncoding]; int data_len = [_data length]; 
     uint8_t *readBytes = (uint8_t *)[_data bytes]; 
     int byteIndex=0; 
     unsigned int len=0; 
     while (TRUE) { 
      len = ((data_len - byteIndex >= 40960) ? 40960 : (data_len-byteIndex)); 
      if(len==0) 
       break; 
      uint8_t buf[len]; (void)memcpy(buf, readBytes, len); 
      len = [self.outputStream write:(const uint8_t *)buf maxLength:len]; byteIndex += len; 
      readBytes += len; } 
    } 
} 

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode 
{ 
    switch(eventCode) { 
     case NSStreamEventNone: 
      break; 

     case NSStreamEventOpenCompleted: 
      break; 

     case NSStreamEventHasBytesAvailable: 
      break; 

     case NSStreamEventHasSpaceAvailable: 
//  { 
//   uint8_t *readBytes = (uint8_t *)[_data mutableBytes]; 
//   readBytes += byteIndex; // instance variable to move pointer 
//   int data_len = [_data length]; 
//   unsigned int len = ((data_len - byteIndex >= 1024) ? 
//        1024 : (data_len-byteIndex)); 
//   uint8_t buf[len]; 
//   (void)memcpy(buf, readBytes, len); 
//   len = [stream write:(const uint8_t *)buf maxLength:len]; 
//   byteIndex += len; 
//   break; 
//  } 

     case NSStreamEventErrorOccurred: 
      break; 

     case NSStreamEventEndEncountered: 
      break; 

      // continued ... 
    } 
} 


-(void)disconnect{ 

    NSLog(@"disconnect method called"); 

    NSStreamStatus socketStatus = [self.outputStream streamStatus]; 
    int status = socketStatus; 
    NSLog(@"Stream Status is %i", status); 

    if (status == 2) { 
     [self.inputStream close]; 
     [self.outputStream close]; 
     NSLog(@"Socket Closed"); 
    } 
} 

- (void)deallocMe 
{ 
    [TESTtcpController dealloc]; 
} 

@end 

回答

2

您應該使用AFNetworking庫。圖片上傳將是微不足道的。閱讀關於AFNetworking在這裏:http://cocoadocs.org/docsets/AFNetworking/2.0.0/

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"]; 
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
    if (error) { 
     NSLog(@"Error: %@", error); 
    } else { 
     NSLog(@"Success: %@ %@", response, responseObject); 
    } 
}]; 
[uploadTask resume]; 
+0

+1的信息。如果這樣做的話,你會得到支票。 :-) – Patricia

+0

我們幾乎在那裏......我收到以下錯誤:Error:Error Domain = kCFErrorDomainCFNetwork Code = 303「The operation could not be completed。(kCFErrorDomainCFNetwork error 303.)」UserInfo = 0x16ea6030 {NSErrorFailingURLKey = http:// 10.10.10.10:10101/,NSErrorFailingURLStringKey = http:// 10.10.10.10:10101/} – Patricia

+0

我不得不添加空格來顯示http部分並使其不成爲鏈接。是否還有其他一些事情需要完成。把它包裝在POST或其他東西? – Patricia