简体   繁体   中英

Conduct a method when a device is offline with Parse in Objective-C and Swift

I would like to know how to conduct a method when Parse notifies that the device is offline. I know that Parse posts an error message in the output section of Xcode, notifying that the device is offline. However, I do not know how to conduct a method when the error gets posted. I attached the code I am using. Thank you!

 NSData *imageData = UIImageJPEGRepresentation(self.image, 1.0);
    PFFile *parseImageFile = [PFFile fileWithName:@"uploaded_image.jpg" data:imageData];
    [parseImageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (!error) {
            if (succeeded) {
                //Putting the photo in Parse
                PFObject* posts = [PFObject objectWithClassName:@"Tops"];
                posts[@"imageText"] = clothesName;
                posts[@"uploader"] = [PFUser currentUser];
                posts[@"imageFile"] = parseImageFile;
                [posts saveInBackground];
                NSLog(@"success!!");

You are probably better off using Reachability, as it is the standard class for handling questions of connectivity. I recommend Tony Million's implementation that is a drop-in replacement (upgrade). It can be found here: https://github.com/tonymillion/Reachability

A short example of how to use it, from the documentation:

// Allocate a reachability object
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];

// Set the blocks
reach.reachableBlock = ^(Reachability*reach)
{
    // keep in mind this is called on a background thread
    // and if you are updating the UI it needs to happen
    // on the main thread, like this:

    dispatch_async(dispatch_get_main_queue(), ^{
      NSLog(@"REACHABLE!");
      //Do the things you need to do with Parse here
    });
};

reach.unreachableBlock = ^(Reachability*reach)
{
    NSLog(@"UNREACHABLE!");
    //Wuh woh. Fire off an alert letting the user know there's no connection.
};

// Start the notifier, which will cause the reachability object to retain itself!
[reach startNotifier];

Want another reason to use Reachability? It is also what Parse recommends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM