I'm developing an app using UITabBarController. More specifically, using the storyBoard. I want all of my tab to be able to send and receive data from the server.
Problem is i don't know how. Only the first tab that have initNetworkCommunications is able to send and receive from the server. So what should i do in order for my app be to be able to send and receive from the other tabs?
I've found that using NSNotificationCentre to handle the data would work but is there another way?
Here's the code for creating the socket connection
-(void)initNetworkCommunication
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)#"169.254.1.1", 2000, &readStream, &writeStream);
inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
lets say i have 2 tabs. The first tab has a connect button which is used to call initNetworkCommunication. From this tab i'm able to send and receive data. But what do i do with the other tab? Is there a way to link this connection over?
i've tried to import each other's controller and use [FirstController sendMessage]; from the secondViewController but doesn't seem to work.
Creating a singleton is fine, what I've done is instead of making a class function (which would force your network to re-init the connection every time you switch tabs) I make the networkconnector a property on a custom implementation of tabBar:
#import <Foundation/Foundation.h>
#import "NetworkController.h"
#interface NetworkStorageTabBarController : UITabBarController
#property (nonatomic, strong) NetworkController *thisNetworkController;
#end
And the implementation file:
#import "NetworkStorageTabBarController.h"
#implementation NetworkStorageTabBarController
#synthesize thisNetworkController;
#end
Then when I load up my tabbed view, I call this in viewWillAppear of the first view that will appear:
//set up networking
NetworkStorageTabBarController *thisTabBar = (NetworkStorageTabBarController *) self.tabBarController;
self.thisNetworkController = thisTabBar.thisNetworkController;
self.thisNetworkController.delegate = self;
So far, this has worked gloriously for me. Took me forever to figure it out, so I hope this helps!
The simplest way is to create a Singleton, let's call it NetworkCommunications.
To make it Singleton (only one instance will be created):
+(NetworkCommunications *)sharedManager {
static dispatch_once_t pred;
static NetworkCommunications *shared = nil;
dispatch_once(&pred, ^{
shared = [[NetworkCommunications alloc] init];
});
return shared;
}
Then you simply call [NetworkCommunications sharedManager] from your tabs to get access to that single instance.
You put your network code in that instance as well.
Related
I've got the following code, which I know is being run:
ReadDelegate * del = [[ReadDelegate alloc] init];
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)(#"server.com"), port, &readStream, &writeStream);
NSInputStream * readSock = (__bridge_transfer NSInputStream*)readStream;
[readSock setDelegate:del];
[readSock scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
NSOutputStream * writeSock = (__bridge_transfer NSOutputStream*)writeStream;
[writeSock scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
NSLog(#"Open socket");
[readSock open];
[writeSock open];
[writeSock write:(uint8_t*)("request\0\0\0") maxLength:10];
while (YES) {
//I'm skipping over inconsequential stuff
}
NSLog(#"finished reading");
[readSock close];
[writeSock close];
return [del getMessage];
My ReadDelegate class is declared like #interface ReadDelegate : NSObject <NSStreamDelegate> and includes a - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode. That particular function just has a print statement in it to see if it's ever being called. It's not.
I know for a fact that the connection is being opened because my server is receiving the "request\0\0\0" message and the server is sending the file (I have tests in other environments which can receive the file just fine).
However, as mentioned, the ReadDelegate object declared in the beginning (del) never receives the stream message, even once (to say the stream is open or whatever).
Why is the delegate not being called?
It looks like your stream doesn't receive events because of your while loop.
Every new event from a stream can be handled in a new iteration of run loop. But the new iteration can not be started because the current one never finishes.
I am a newbie in Objective-C. I am trying to learn how to work with NSStream. I just used simple code from Apple Support. This code should open a stream from a file in my Desktop and show a simple message when the delegate is called by iStream. At the end of the code, I can see the status is correct, but the delegate never gets called. What am I missing?
#import <Foundation/Foundation.h>
#interface MyDelegate: NSStream <NSStreamDelegate>{
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode ;
#end
#implementation MyDelegate
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
NSLog(#"############# in DELEGATE###############");
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool {
MyDelegate* myDelegate=[[MyDelegate alloc]init];
NSInputStream* iStream= [[NSInputStream alloc] initWithFileAtPath:#"/Users/Augend/Desktop/Test.rtf"];
[iStream setDelegate:myDelegate];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[iStream open];
NSLog(#" status:%#",(NSString*) [iStream streamError]);
}
return 0;
}
The run loop isn't running long enough for the delegate method to be called.
Add:
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
right after you open the stream. This is only necessary in a program without a GUI -- otherwise the run loop would be spun for you.
If you want to be absolutely sure that stream:handleEvent: has been called before exiting, set a (global) flag in that method and put the runUntilDate: in a while loop that tests for the flag:
while( !delegateHasBeenNotified ){
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
}
I try to open a TCP stream to speak to a device with a cocoa app.
I searched the web and found that there is some possibilities to do that but i'm a little bit stuck.
I decided to use the NSStream way (because it's referenced in cocoa-touch, will be usefull if i want to port my app to iPhone i presume), so here is my code:
#implementation AppDelegate
- (IBAction)connect:(id)sender {
[NSStream getStreamsToHost:"192.168.1.4" port:23 inputStream:&inputStream outputStream:&outputStream];
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
// Both streams call this when events happen
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
if (aStream == inputStream) {
[self handleInputStreamEvent:eventCode];
} else if (aStream == outputStream) {
[self handleOutputStreamEvent:eventCode];
}
}
- (void)handleInputStreamEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {
case NSStreamEventHasBytesAvailable:[self readBytes];
break;
case NSStreamEventOpenCompleted:
// Do Something
break;
default:
case NSStreamEventErrorOccurred:
NSLog(#"An error occurred on the input stream.");
break;
}
}
So, when I click on my connect button, it is supposed to open the stream to my host and make my 2 objects (inputstream and outputstream)
The first step I would like to reach is to have the inputStream in a NSTextView and know if the host has been reached or not... but i'm still stuck :(
If someone can light my way, it would be nice! I'm new on Stack Overflow and I'll be glad to help the community on somethings that i know much! :)
I updated my code and it seems that the light is coming, slowly but it's coming :)
I made a stream to a telnet server. I got the "hello" in a texview.
Now, I would like to send the user & password to be able to send commands to the server, but here is my "send user & pass" button code:
- (IBAction)sendusername:(id)sender {
NSString * usernameMsg = [NSString stringWithFormat:#"user #", [usernameField stringValue]];
NSData * usertosend = [[NSData alloc] initWithData:[usernameMsg dataUsingEncoding:NSUTF8StringEncoding]];
[outputStream write:[usertosend bytes] maxLength:[usertosend length]];
}
Follow my searchs, the server should respond me a thing like "user +ok" but nothing...
2 stranges things:
- If I open the socket to a FTP server of SSH server, I've always the "hello" response without problem. But in telnet, 90% of connections respond me a strange hello like this: "ÿýÿýÿûÿû", why?
When I send the user, nothing happen, only an unrocognized event from the handleEvent...
I can suggest you to look at https://github.com/robbiehanson/CocoaAsyncSocket/, a nice Objective-C wrapper for BSD sockets. It allows you to handle the send-receive interactions on the event loop in nice and clean callback manner (it even handles custom "message terminating" symbols for you allowing to concentrate more on actual packet handling rather then on combining and splitting the stuff you receive from wire).
I'm learning Cocoa...
I tried different way to do that but I'm still in the black...
I have this method in my implementation:
- (void)closeStream:(NSStream *)theStream {
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
How can I call it from an IBAction in my #synthetize?
- (IBAction)connect:(id)sender {
if ([[connectNOK stringValue] isEqualToString:#"Disconnected"]) {
[connectButton setTitle:#"Disconnect"];
NSString * hostFromField = [hostField stringValue];
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)hostFromField, [portField intValue], &readStream, &writeStream);
inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
} else {
[connectButton setTitle:#"Connect"];
// I want to call this method here
}
}
If the closeStream: method is defined in the same class than the connect: method, you'll have to use:
[ self closeStream: someStream ];
Where someStream is the NSStream object you need to pass.
The self keyword refers to the current instance of the class.
If you don't know that, or what it means, I suggest you take a look at the Objective-C language basics before trying to do/code anything, and maybe after, the complete language reference.
EDIT:
I can see in your code that your connect: method «toggles» the connection based on the value of a button label.
This is not a very good design, for you to know, but you'll have other problems here.
I guess you want to close the input and output streams, if necessary.
The problem is, when the connect method is called a second time, the inputStream and outputStream variables are not accessible anymore, as they are local variables.
You probably need to store them as instance variables instead, so you can refer to them later on.
Once again, it seems you really should start by reading some documentation about programming principles, as well as some Object-Oriented programming principles.
Don't try to go too fast. Knowledge is the key to everything, so start by reading the documentation I mentioned before.
I wrote a quick objective-C method that uses Amazon's AWS iOS SDK to synchronously download a file from my Amazon S3 Bucket in my iPad app. This is an enterprise app, and I am using reachability to detect WiFi before allowing synchronization with S3. It is working fine for short downloads (those in kilobytes), but with files that are around 20-30 megs, it will continue to download into the stream and the file will continue growing. I've not let it go to see if it will eventually stop/crash, but I've watched a file that was 30 megs go past 90 megs in my iOS Simulator. I've read into several cold threads where some have experienced the same and I really need an answer.
Here is my method...
- (void)retrieveRemoteFile:(NSString *)fileName {
NSString *destinationFileName = [NSString stringWithFormat:#"%#%#",[self getBucketDirectory],fileName];
AmazonS3Client *s3 = [[[AmazonS3Client alloc] initWithAccessKey:ACCESS_KEY_ID withSecretKey:SECRET_KEY] autorelease];
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:destinationFileName append:NO];
[stream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[stream open];
S3GetObjectRequest *request = [[S3GetObjectRequest alloc] initWithKey:fileName withBucket:BUCKET];
request.outputStream = stream;
[s3 getObject:request];
[stream close];
[stream release];
[request release];
}
Re-evaluating the situation, I'd really like to get my method using an ASynchronous Request and use a S3RequestDelegate object to help me update the bytesIn as it's downloading. In their archive, there is a sample in S3AsyncViewController that should show how to do what I want. I've added S3RequestDelegate.h/.m into my project, and implemented a S3RequestDelegate in my .h like this...
#import "S3RequestDelegate.h"
... {
S3RequestDelegate *s3Delegate;
}
I've altered my retrieveRemoteFile method to look a little like this (it's changed all day and I haven't gotten anywhere)
- (void)retrieveRemoteFile:(NSString *)fileName {
NSString *destinationFileName = [NSString stringWithFormat:#"%#%#",[self getBucketDirectory],fileName];
AmazonS3Client *s3 = [[[AmazonS3Client alloc] initWithAccessKey:ACCESS_KEY_ID withSecretKey:SECRET_KEY] autorelease];
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:destinationFileName append:NO];
//[stream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
//[stream open];
S3GetObjectRequest *request = [[S3GetObjectRequest alloc] initWithKey:fileName withBucket:BUCKET];
request.outputStream = stream;
s3Delegate = [[S3RequestDelegate alloc] init];
[request setDelegate:s3Delegate];
[s3 getObject:request];
//[stream close];
//[stream release];
//[request release];
}
As you can see, I've set the S3GetObjectRequest delegate with setDelegate to my S3RequestDelegate pointer s3Delegate. I've added breakpoints in all of the delegate methods of the S3RequestDelegate object, but none of them are executing. In looking for a received file on my simulator, nothing is even getting downloaded now.
The sample makes it look like all you need to do is set a delegate to make it asynchronous. It also makes it look like you don't need to manage the stream object, and whether you do or not, nothing gets downloaded. I'm setting the delegate and it's never running any of the delegate methods; didReceiveResponse, didCompleteWithResponse, didReceiveData, didSendData, totalBytesExpectedToWrite, didFailWithError or didFailWithServiceException.
I was setting up my request to run in an OperationsQueue. Removed this code and kick off the Asynchronous transfer on the main thread and the delegate functions handle transferring the next file in the array. I've incorporated a status bar and cancel button and it worked out great.