Sending multiple url requests with NSURL Connection - objective-c

I need to send data many times within one view. I have about 6 UISwitches and every time there value gets changed, I need to send (via a POST method) data (a simple NSString) to my php script (http://www.mydomain.com/script/dowork.php)
I have been struggling over the last couple of days in doing this since I have only managed to get this to work with only 1 switch but not when users change multiple switches. If someone can please give me an example of how to do this it would mean a lot.
EDIT
This is how Im doing it now:
-(IBAction)switchSelector:(id)sender {
switch ([sender tag]) {
case 0:
if (switchMax.on) {
//here I Send it to the method that will make the connection
[self registerWithServer:#"Tokens"];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool: switchMax.on forKey: K_SWITCH_KEY];
[defaults synchronize];
} else {
//other stuff
}
break;
}
}

How did you manage to do it with one switch? Could you post the code as well?
For multiple switches just hook up your method with the valueChanged in interface builder. Inside that method check which switch is on - if ([mySwitch1 isOn]), edit your NSString and send it.

Just some thoughts, but do you really need to send the changes to your server immediately? Assuming that these switches are used in some settings panel, you could save the settings once the user is done with the panel and send it to your server, e.g. when they press the Done button or exit from this view. This way, you only send the request once without having to be burdened with sending it multiple times.
Keep in mind that the user is on a mobile device and you should try to keep data usage as low as possible.

Related

Parse PFObject fetch not working

I'm trying to update PFObjects with server information, basically to discard local changes when user cancels actions, but I''m having a hard time. I'm not sure if I'm missing something or it's a bug, it has been a long programming session.
Here is a test code:
PFObject *object = [PFObject objectWithoutDataWithClassName:#"UserRecipes" objectId:#"1NOxhVZVXJ"];
object[#"instructions"] = #"TEST INSTRUCTIONS";
NSLog(#"%#", object[#"instructions"]);
[object fetch];
NSLog(#"%#", object[#"instructions"]);
I've tried with different objects and classes to make sure it isn't something related to acl. By the way, in one particular PFQueryTableViewController, when I change the object with the method above, no success, but when I leave the controller and enter again, forcing everything to be reloaded, the object is fetched with data from the server and local changes are gone.
UPDATE:
As I temporary solution, I'm using [PFObject revert] to discard changes and it works. But I would really prefer to perform tasks in background using fetchInBackground.

Testing internet connection on iPad app using ios5

I have been searching through the forum regarding how to check whether there is internet or not in my ipad app. I just created a simple webview project with other view controllers and I need to display a UIAlert message when the internet is not available. In my case it is displaying the message when I run the app. When I run the app with internet and then deactivate the internet, it does not show the UIAlert message, that is if I switch between the views, it does not any more show the no internet connection.
I have followed this way of implementation in my project: (sorry my mistake this is the link I followed) http://mozymac.com/forums/f54/how-check-if-there-internet-connection-iphone-os-devices-595/ [This is the new edited question]
Apart from that I went through some of the previous questions in Stackoverflow forum like for ex: How to check for an active Internet connection on iOS or OSX?
But everybody has their own version. If any one has a much more updated method for ios5, xcode 4.2.1 of how to accomplish this then would be helpful for me.
Thanks
Is there a reason why you want to check for internet connection before actually trying to load a request in the UIWebView?
Best practice is to just start loading, and use your UIWebViewDelegate/NURLConnectionDelegate to inspect the NSError to see what is wrong. In case of network failure you will receive an error with a domain equal to NSURLErrorDomain. The error code will indicate what the problem is, see the NSError codes enum.
And only after the first error start your reachability to see when the internet connection becomes available again. Or easier, just let the user retry.
Using the Reachability code will actually cause some overhead. It takes time to check if the internet is available, which you could just have used to set up the actual connection as well.
Example
Since you are using a UIWebView you should implement the following delegate method to be notified of errors.
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
if (![[error domain] isEqualToString:NSURLErrorDomain]) {
// not a nsurl error, take other appropriate action
return;
}
NSInteger code = [error code];
// show appropriate error to user, based on code
}
In this delegate method you should do whatever is needed to achieve what you want. You could retry the request yourself, show a message to the user or start listening for reachability changes using the code from the Reachability example provided by Apple.
Apple has one, it's called Reachability. Here's the link to it.
http://developer.apple.com/library/ios/ipad/#samplecode/Reachability/Introduction/Intro.html
Best way to check internet connection is Reachibility application
link
Or else
+ (BOOL)isNetworkAvailable
{
CFNetDiagnosticRef diag;
diag = CFNetDiagnosticCreateWithURL (NULL, (CFURLRef)[NSURL URLWithString:#"www.apple.com"]);
CFNetDiagnosticStatus status;
status = CFNetDiagnosticCopyNetworkStatusPassively (diag, NULL);
CFRelease (diag);
if ( status == kCFNetDiagnosticConnectionUp )
{
//NSLog (#"Connection is up");
return YES;
} else {
NSLog (#"Connection is down");
return NO;
}
}

How to get the application terminated notification quickly cocoa

To get the application terminated notification I have something like the following
NSNotificationCenter* center = [[NSWorkspace sharedWorkspace] notificationCenter];
[center addObserver:self
selector:#selector(appTerminated:)
name:NSWorkspaceDidTerminateApplicationNotification
object:nil
];
- (void)appTerminated:(NSNotification *)note
{
NSLog(#"+ appTerminated");
}
actually my concern is when the firefox application quits/restarts,I need to update its database.When the firefox quits manually I can update with the help of appTerminated as firefox releasing its lock to the database.When it is running state,I am not able to update the database as firefox is locking it.when the firefox is restarted ,it is quitting and restarting too quickly so that I cannot update the database as it is in running stateI need to update database before it restarts.i.e.when the firefox is in quit state.
So,I need the notification just before firefox is going to quit.
Is any api availabe for this or please give some ideas.
Thanks in advance
I take it you have two applications, one that watches the other. Your concern seems to be that you don't want the watched app to start really doing anything until the watcher finishes its work.
You just need to communicate between the processes in this case. The watched application should wait until the watcher finishes its work. You can achieve this using a lock, or you could use NSDistributedNotification (or other IPC mechanism) to send messages from the watcher to the watched to let it know it may continue.
I prefer the locking mechanism since it behaves correctly if the watcher fails. The most correct place to put the lock would be on the database, since that's the resource you're trying to protect.
I would try something like that:
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
if (isMyDatabaseClosed) {
[self closeMyDatabaseAndQuit];
return NSTerminateLater;
} else {
return NSTerminateNow;
}
}
-(void)closeMyDatabaseAndQuit
{
/* close your database, etc...*/
[NSApp replyToApplicationShouldTerminate: YES];
}
The code is not tested, but you should get an idea.

Where to put reachability check to ensure data to be loaded before viewing it?

I have read
this question and found its answer to be useful to check an internet connection for the iPhone. I implemented the check in my viewDidLoad message.
However my App does load Data from an XML file from a server (within viewWillAppear). In this case the check has to be done before the app tries to load the data from the internet source. My problem here is that the network check requires some seconds but the app does proceed with the code.
This results in delaying the check. So there is a valid internet connection, but the bool variable that stores this information is set too late.
Code in viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];
The selected message is implemented in the same way like in the example in the link above. Additionally it sets some bool-properties so I can access the connection state within the app.
Code in viewWillAppear
if(internetActive == TRUE)
{
NSLog(#"connected");
//Code to load XML stuff
}
else
{
NSLog(#"not connected");
}
The console shows me "not connected". But a few seconds later the debug logs within "checkNetworkStatus" show me that the internet connection is available and the bool "internetActive" would be set.
I assume that the network check delivers his report about the connection state too late for my purpose. Is there a way to delay the app until the connection is established? Or would this lead to crashing the app cause the view isn't displayed within a few seconds?
Are there any other possibilities to ensure the connection?
My second question is how to ensure a specific internet address is available? I the link above there is mentioned
hostReachable = [[Reachability reachabilityWithHostName: #"www.apple.com"] retain];
[hostReachable startNotifier];
to detect the connection to a host, but I want to go in detail and try to detect if the host deserves a specific address or not. But entering the full address path (e.g. "localaddress.mylan.de/lan/xml/") instead of the host leads to a not reachable connection state for the host. Entering the mentioned address in the browser address bar shows me the correct result. I guess I have to check it otherwise but how?
Thanks for reading :)
After getting more experiences with IOS development my first question is solved with three steps.
First step is to start all necessary notifiers once. This can be done by starting them in viewDidLoad of the first loaded ViewController.
Check current connection state by evaluating property named currentReachabilityStatus of reachability-objects. This state can be "not connected" even if a connection is available. This happens if the check is done within the ViewController who is starting the notifier. Reason for this is the time it takes while the notifier recognizes the connection. If currentReachabilityStatus property is evaluated as connected then data loading processes can be started.
Evaluating the connection state within the method whose selector is added during adding the notifier. This method will start every time the connection state changes. First call will be directly after starting the notifier. If connection state is evaluated as connected then data loading processes can be started.
The second question stays unresolved up to now. May be there is no way other than sending a request to the target and waiting for a response or a timeout.
Did you try dispatch_async & dispatch_sync(dispatch_get_main_queue( reload data here ) ?

UIWebView capture post

I am looking for a starting point on a project that needs to display a UIWebView on an iPad. THe catch is that the HTML will be generated by the pad and displayed in the UIWebView, and will contain many input controls.
What is needed is a way to grab the contents of these controls after the user has completed entry similar to how I would do it on a server. I need to grab this entered data on the iPad without an actual submit.
Does anyone know the starting point for this type of interaction?
You can do this by implementing the UIWebViewDelegate delegate's shouldStartLoadWithRequest method:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSData* data = request.HTTPBody;
NSString* s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if([s length] == 0)
return YES;
else
return NO;
}
It works fine with a post.
Within the previously posted article it also mentioned the UIWebViewDelegate method,
webView:shouldStartLoadWithRequest:navigationType:
This gets invoked on the delegate before a link is followed. I haven't tried it, but this method might be invoked when submitting the form. Use a GET method. Easier than having to loop out of the app and back.
It can be done in simple way..
we know HTTP request contains -
Method (GET,POST..etc)
HTTP header
HTTP body
we can check header field value for Conent-type if it is x-www-form-urlencoded
then form field values are sending thru them as key=value pairs
then we can catch therse paires in
webView:shouldStartLoadWithRequest:navigationType: - in request parameter as
[request HTTPBody], similarly we can get method [HTTPMethod]..etc
if it is simply GET method then all pairs will be in request itself.
:) hope it helps
Here's a way to do it:
Register a custom URL scheme for your App (see here f.e. http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html)
When the user touches your save/submit/whatever button you read out the values of all needed form-fields, construct a url that matches your URL scheme and redirect to this URL with JavaScript (window.location) and work with the data in Objective-C and do what you have to do.
Example URL could be: myapp://value_of_field1/value_of_field2/...
See the linked tutorial on how to register a custom scheme and how to retrieve the data in Obj-C.