I created messaging application like whatsApp and hike. Its working on 3G,4G and Wifi network. when user switch to 2G network my app connection is interrupted but whatsApp and hike working perfectly. I posting code where i manage app connection ::
#pragma mark - connect to the server
- (BOOL)connect {
if (!self.xmppStream) {
[self setupStream];
}
NSString *jabberID = [[NSUserDefaults standardUserDefaults] stringForKey:kUserName];
if (![self.xmppStream isDisconnected]) {
return YES;
}
if (jabberID == nil || kXMPPPassword == nil) {
return NO;
}
[self.xmppStream setMyJID:[XMPPJID jidWithString:jabberID]];
[self.xmppStream setHostName:kXMPPHost];
NSError *error = nil;
if (![self.xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
// UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"Can't connect to server %#", [error localizedDescription]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
// [alertView show];
NSLog(#"errorerrorerrorerrorerrorerror :- %#", error);
return NO;
}
return YES;}
- (void)connectThenSignIn {
if ([_xmppStream isConnecting]) { // Connection error, connection is being established
return ;
}
if ([_xmppStream isDisconnected]) { // If disconnected, a server connection is established
[self connect];
_goToRegisterAfterConnected = NO;
} else if ([_xmppStream isConnected]) {
[self doSignIn];
} }
Please suggest me best way to manage openfire connection on every network (2G, 3G, 4G and wifi).
Those applications are probably using push notifications to receive updates while on unreliable IP networks (like 2G). This allows them to appear online without maintaining a constant connection to a server.
This is difficult to accomplish with XMPP -- the protocol was written with the assumption that users only need to be reachable while they are connected to the server. Some XEP extensions have added partial workarounds, but the protocol as a whole is poorly suited to mobile clients. (This has been a well-known limitation since at least 2014.) You may want to consider alternatives.
Related
I have a query regarding concurrency in Azure mobile client SDK.
for windows I found Conflict link for handling concurrency but I could not found the same for iOS client SDK.
Can anyone please suggest or help how to handle concurrency in iOS client SDK.
Here is the old Mobile Services page for handling conflicts with the iOS SDK. The setup for offline sync with the iOS SDK hasn't changed since then.
1) Set up an MSSyncContextDelegate and pass it to the MSSyncContext constructor when you create it.
2) Implement tableOperation:(MSTableOperation *)operation onComplete:(MSSyncItemBlock)completion in your delegate. After executing the operation, check for an MSErrorPreconditionFailed error code and decide what to do from there based on your app's needs.
- (void)tableOperation:(MSTableOperation *)operation onComplete:(MSSyncItemBlock)completion
{
[operation executeWithCompletion:^(NSDictionary *item, NSError *error) {
NSDictionary *serverItem = [error.userInfo objectForKey:MSErrorServerItemKey];
if (error.code == MSErrorPreconditionFailed) {
QSUIAlertViewWithBlock *alert = [[QSUIAlertViewWithBlock alloc] initWithCallback:^(NSInteger buttonIndex) {
if (buttonIndex == 1) { // Client
NSMutableDictionary *adjustedItem = [operation.item mutableCopy];
[adjustedItem setValue:[serverItem objectForKey:MSSystemColumnVersion] forKey:MSSystemColumnVersion];
operation.item = adjustedItem;
[self doOperation:operation complete:completion];
return;
} else if (buttonIndex == 2) { // Server
NSDictionary *serverItem = [error.userInfo objectForKey:MSErrorServerItemKey];
completion(serverItem, nil);
} else { // Cancel
[operation cancelPush];
completion(nil, error);
}
}];
NSString *message = [NSString stringWithFormat:#"Client value: %#\nServer value: %#", operation.item[#"text"], serverItem[#"text"]];
[alert showAlertWithTitle:#"Server Conflict"
message:message
cancelButtonTitle:#"Cancel"
otherButtonTitles:[NSArray arrayWithObjects:#"Use Client", #"Use Server", nil]];
} else {
completion(item, error);
}
}];
}
I am working on an iOS chat app where user login to app. I've downloaded XMPPFramework from GitHub XMPPFramework. I am trying to connect XMPP framework with Openfire server by following this tutorial. Here is my code to connect XMPP to openfire.
- (BOOL)connect {
[self setupStream];
[xmppStream setHostName:#"192.168.1.5"];
[xmppStream setHostPort:5222];
NSString *jabberID = [[NSUserDefaults standardUserDefaults] stringForKey:#"userID"];
NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:#"userPassword"];
if (![xmppStream isDisconnected])
return YES;
if (jabberID == nil || myPassword == nil)
return NO;
[xmppStream setMyJID:[XMPPJID jidWithString:jabberID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream isConnected])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"Can't connect to server %#", [error localizedDescription]]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
return NO;
}
return YES;
}
The problem is when I run the app, it shows the alert can't connect to server. I have checked many questions on StackOverflow and tried googling but couldn't find any relevant solution. How to connect it to the Openfire serve? If I am doing anything wrong in my code please suggest me with a snippet of code or a tutorial to make this happen.
A host of possibilities.
Try adding break points at xmppStreamDidConnect and xmppStreamDidAuthenticate.
If xmppStreamDidConnect isn't reached, the connection is not established; you've to rectify your hostName.
If xmppStreamDidAuthenticate isn't reached, the user is not authenticated; you've to rectify your credentials i.e. username and/or password.
One common mistake is omitting of #domainname at the back of username i.e. username#domainname e.g. keithoys#openfireserver where domain name is openfireserver.
Hope this still relevant, if not, hopefully it will help others.
There are some issues with your code:
I don't see the call to connect, you should add something like this:
NSError *error = nil;
if (![_xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error connecting"
message:#"Msg"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
Most of the XMPP API is asynchronous.
You have to set the stream delegate in order to receive events.
Check out XMPPStreamDelegate and XMPPStream#addDelegate
If you don't want to go through the code yourself XMPPStream.h
, you can implement all methods of XMPPStreamDelegate and log the events. This will help you understand how the framework works.
Hope this helps, Yaron
I want to connect to openfire server anonymously using xmpp framework in iOS. I can connect to open fire by providing the JID and PW. However when I tried to connect anonymously it says "The server doesn't support anonymous authentication".
I'm using a button in xib file. When its clicked below code executes:
- (IBAction)login:(id)sender {
[[self appDelegate]connect];
NSError *authenticationError = nil;
[self.xmppStream authenticateAnonymously:&authenticationError];
}
and below is the code for connect method:
- (BOOL)connect {
[self setupStream];
xmppStream.hostName = #"abc.xyz.com";
//xmppStream.hostName = #"Virtuals-MacBook-Pro.local ";
NSString *jabberID = [[NSUserDefaults standardUserDefaults] stringForKey:#"userID"];
NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:#"userPassword"];
if (![xmppStream isDisconnected]) {
return YES;
}
if (jabberID == nil || myPassword == nil) {
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:jabberID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"Can't connect to server %#", [error localizedDescription]]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
//[alertView release];
return NO;
}
return YES;
}
Steps for anonymous authentication:
1- First of all connect the xmpp-stream, then authenticate anonymously.
[[self xmppStream] authenticateAnonymously:&error];
then you will be authenticated anonymously. but a very important thing. before authenticating, get the username and password of a registered user and connect to the xmpp-stream
The accepted answer is almost right but is mixing things (connection and authentication)
What you are facing is probably a server side configuration problem, if your server does not allow you to log in anonymously you cannot, period.
Anyway you can still try to connect anonymously and handle the fact that you are not allow, for that you need to:
1) Set your JabberID to anonymous#domain (were domain is your server domain)
[self.xmppStream setMyJID:[XMPPJID jidWithString:#"anonymous#domain"]];
2) With that in place you can connect to the server (you do not need a valid user as the accepted answer pointed out)
[self.xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error]
3) Once you get response from the sever your XMPP delegate method didConnect will be called, in there you check if the server configuration supports anonymous authentication and if so try to authenticate anonymously
- (void)xmppStreamDidConnect:(XMPPStream*)sender
{
self.isXmppConnected = YES;
if ([self.xmppStream supportsAnonymousAuthentication]) {
NSError* error = nil;
//the server does support anonymous auth
[self.xmppStream authenticateAnonymously:&error];
}
else {
NSLog(#"The server does not support anonymous authentication");
}
}
4) You handle however you want the situations were the server does not support anonymous auth (maybe trie with a well know user or display a warning to the user) or you get an error authenticating (network issues)
I am trying to setup Reachability using the new 2.0 AFNetworking.
In my AppDelegate I initialise the sharedManager.
// Instantiate Shared Manager
[AFNetworkReachabilityManager sharedManager];
Then in the relevant VC method I check to see if isReachable:
// Double check with logging
if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
NSLog(#"IS REACHABILE");
} else {
NSLog(#"NOT REACHABLE");
}
At present this is not working as expected in the simulator, but I imagine this would need to be tested on device and not simulator.
Question
What I would like to do is monitor the connectivity within the VC. So I run the following in the viewDidLoad:
// Start monitoring the internet connection
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
How would I then register for the changes? What is/would be called once the network connection changes I cannot see this from the documentation.
As you can read in the AFNetworking read me page
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(#"Reachability: %#", AFStringFromNetworkReachabilityStatus(status));
}];
Here's also a link to the official documentation.
I have a singleton AFHTTPRequestOperationManager class. In the singleton has a method:
+(void)connectedCompletionBlock:(void(^)(BOOL connected))block {
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
BOOL con = NO;
NSLog(#"Reachability: %#", AFStringFromNetworkReachabilityStatus(status));
if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
con = YES;
}
if (block) {
[[AFNetworkReachabilityManager sharedManager] stopMonitoring];
block(con);
}
}];
}
Before make a request you call this method that return a block indicating if internet is reachable:
[TLPRequestManager connectedCompletionBlock:^(BOOL connected) {
if (connected) {
// Make a request
}else{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Notice" message:#"Internet is not available." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alertView show];
}
}];
I was just going through your question and all the answers. After that I decided to do all these things once. So, in my existing project I just included the AFNetworking through cocoa-pods and here is the solution which is woking for me completely.
Solution -- First of all AFNetworkReachabilityManager is a singleton class. You don't need to do AppDelegate initialisation for sharedManager.
//[AFNetworkReachabilityManager sharedManager];
#import <AFNetworkReachabilityManager.h>
- (void)viewDidLoad {
//Starting the network monitoring process
[[AFNetworkReachabilityManager sharedManager]startMonitoring];
//Checking the Internet connection...
[[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){
if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
UIAlertView *alertNetFound = [[UIAlertView alloc]initWithTitle:#"Network Found" message:#"Please Wait Until It is loading" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertNetFound show];
}else{
UIAlertView *alertNetNotFound = [[UIAlertView alloc]initWithTitle:#"No Internet" message:#"Please Check Your Internet Connection Honey" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alertNetNotFound show];
}
}];
So, in this case every time the device connects to a network, it will do the startMonitoring process first and after that it will hit the status block every time and will display alert according to the status.
You can do anything according to your choice by replacing the alerts on the status block. I used this to load an webpage automatically from local storage but I removed that code for simplicity.
Its even working with my simulator and Mac mini..
Thanks
Hope this helped.
I use this in the app delegate ->
func reachablityCode() {
AFNetworkReachabilityManager.sharedManager()
AFNetworkReachabilityManager.sharedManager().startMonitoring()
AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock({(status) in
let defaults = NSUserDefaults.standardUserDefaults()
if status == .NotReachable {
defaults.setBool(false, forKey:REACHABLE_KEY)
}
else {
defaults.setBool(false, forKey: REACHABLE_KEY)
}
defaults.synchronize()
})
}
And then this in the base file ->
func isReachable() -> Bool {
return NSUserDefaults.standardUserDefaults().boolForKey(REACHABLE_KEY)
}
I am getting stream on iPad from an IP camera named Foscam. If I open IP in iPad browser then it is working good but when I fetch stream in my application then it gets on frist screen shot and stuck on it. App is not getting continuous streaming from cam. I am using this way
- (IBAction)powerChanged:(id)sender {
UISwitch * s = (UISwitch *)sender;
if( s.on == TRUE){
[self initializeData];
if(![deviceClient connect]){
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Can not connect to T-Rex device!"
message:[[NSString alloc] initWithFormat:#"Could not connec to %# and %d port",deviceClient.host,deviceClient.port]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
[s setOn:FALSE animated:TRUE];
} else {
[self adjustLayout:TRUE];
[self startFrequencyTimer];
}
}else {
[self stopFrequencyTimer];
[self adjustLayout:FALSE];
}
}
-(void)initializeData {
[cameraViewFront loadRequest:[NSURLRequest requestWithURL:[frontCameraClient getVideoStreamURL]]];
}
-(BOOL)connect {
if (udpSocket == nil){
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
}
NSLog(#"host %# and port %i", self.host, self.port);
return [udpSocket connectToHost:self.host onPort:self.port error:nil];
}
- (NSURL *) getURL:(NSString *)forPage {
NSLog(#"front cam IP %#" ,self.host);
return [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:#"http://%#/%#user=%#&pwd=%#",self.host,forPage,self.username, self.password]];
}
-(NSURL *)getVideoStreamURL{
return [self getURL:#"videostream.cgi?"];
}
I figured it out. I am using foscam and foscam provides a list of URLs on this link so I searched my cam model and then tried all the given URLs for MPEG connection type and http://IPADDRESS/videostream.cgi?user=[USERNAME]&pwd=[PASSWORD]&resolution=32&rate=0 URL worked for my case. But still there is a problem that it is working awesome on iOS5 and on iOS6 it still stuck on first frame.
To fix this problem this link helped me a lot. This method works for iOS5 and 6 both.