First of all - I am newbie at iOS 6 programming. I am trying to open a socket connection to remote server when application starts, and run it in some background thread. I have a class - NetworkCommunication.h, and 3 view controllers which I would like to be able to read and write to a stream.
The code:
NetworkCommunication.h:
#import <Foundation/Foundation.h>
@interface NetworkCommunication : NSObject {
NSInputStream* inputStream;
NSOutputStream* outputStream;
}
@property(retain) NSInputStream *inputStream;
@property(retain) NSOutputStream *outputStream;
-(void) initNetworkCommunication;
@end
NetworkCommunication.m
#import "NetworkCommunication.h"
NSOutputStream *outputStream;
NSInputStream *inputStream;
@implementation NetworkCommunication
@synthesize outputStream;
@synthesize inputStream;
- (id) init {
NSLog(@"Start!");
[self initNetworkCommunication];
return 0;
}
- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"127.0.0.1", 7000, &readStream, &writeStream);
inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode ];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
[inputStream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL
forKey:NSStreamSocketSecurityLevelKey];
[outputStream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL
forKey:NSStreamSocketSecurityLevelKey];
NSDictionary *settings = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredCertificates,
[NSNumber numberWithBool:YES], kCFStreamSSLAllowsAnyRoot,
[NSNumber numberWithBool:NO], kCFStreamSSLValidatesCertificateChain,
kCFNull,kCFStreamSSLPeerName,
nil];
CFReadStreamSetProperty((CFReadStreamRef)inputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);
CFWriteStreamSetProperty((CFWriteStreamRef)outputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);
//[outputStream setProperty:NSStreamSocketSecurityLevelTLSv1 forKey:NSStreamSocketSecurityLevelKey];
NSString *response = @"HELLO from my iphone\n";
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}
@end
And I try to start it in any controller or in main.m using: NetworkController *comm = [NetworkController new];
When it reaches this code:
[inputStream open];
[outputStream open];
I got "Thead 1: EXC_BAD_ACCESS (code=1, address=0x10917df0)"
I have no idea how to make it work. I would like to start a thread when the app starts, and to be able to write to the NSOutputStream and read for NSInputStream from any Controller. Is it possible? If so, how?
Thanks in advance