首先 - 我是 iOS 6 编程的新手。我试图在应用程序启动时打开与远程服务器的套接字连接,并在某个后台线程中运行它。我有一个类 - NetworkCommunication.h,和 3 个视图控制器,我希望它们能够读取和写入流。
编码:
网络通讯.h:
#import <Foundation/Foundation.h>
@interface NetworkCommunication : NSObject {
NSInputStream* inputStream;
NSOutputStream* outputStream;
}
@property(retain) NSInputStream *inputStream;
@property(retain) NSOutputStream *outputStream;
-(void) initNetworkCommunication;
@end
网络通讯.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
我尝试在任何控制器或 main.m 中使用以下命令启动它: NetworkController *comm = [NetworkController new];
当它到达此代码时:
[inputStream open];
[outputStream open];
我得到“头 1:EXC_BAD_ACCESS(代码=1,地址=0x10917df0)”
我不知道如何使它工作。我想在应用程序启动时启动一个线程,并且能够写入 NSOutputStream 并从任何控制器读取 NSInputStream。可能吗?如果是这样,怎么做?
提前致谢