简体   繁体   English

当设备在Objective-C和Swift中处于离线状态时执行一种方法

[英]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. 我想知道当Parse通知设备离线时如何执行一种方法。 I know that Parse posts an error message in the output section of Xcode, notifying that the device is offline. 我知道Parse在Xcode的输出部分中发布了一条错误消息,通知该设备处于脱机状态。 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). 我建议使用Tony Million的实现,该实现是直接替代(升级)的。 It can be found here: https://github.com/tonymillion/Reachability 可以在这里找到: 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. 这也是Parse建议的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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