7
votes

I tried to send data from iPhone app to watch kit extension but fail. And have no idea how to do it.

I tested on simulator and send data via app groups.

Here is my steps:

  1. download watch kit catalog sample app from apple
  2. Add App groups (XXX.XXX.XXX) for iPhone app and wtach kit extension
  3. Add RequestOpenAccess: YES for NSExtensionAttributes (watch kit extension)
  4. Add a button to iPhone app that will write a value to NSUserDefaults with the specific Suite Name
  5. Add code at watchkit extension to read NSUserDefaults data. ([NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:)

  6. Run watch kit app

  7. manual click the Catalog app in the iPhone simulator
  8. click the button added at step 4
  9. add break point at watchkit extension to see if the NSUserDefaults value changed
  10. Nothing happen

What necessary things I miss?

Or I should use another way to do this?

All I want to do is to send data from iPhone to watch every seconds. The data could be string or image.

Thanks

2
Can you share some code? Are you sure you wrote the file properly for the app group? - Idan

2 Answers

1
votes

To set communication between iPhone and iWatch I have been putting a file into the shared app group folder and monitor it from the Watch extension. If there is any change in iPhone app it modifies the file and the Watch extension will be notified and can act on it.

1
votes

You need to:

  1. Create an app group on both targets (iPhone and Watch extension). Make sure it is added on your App ID on apple developer portal (sometimes it doesn't pass well from Xcode).

  2. Write to the app group from the iPhone app:

    NSString *destFolderPath = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:
                               @"YOUR_GROUP_STRING"].path;
    [UIImageJPEGRepresentation(image, 1.0) writeToFile:[destFolderPath stringByAppendingPathComponent:@"Your_Shared_File_Name.jpg"] atomically:YES];
    
  3. Read the file from the extension:

    UIImage *image;
    NSURL *groupURL = [[NSFileManager defaultManager]
                   containerURLForSecurityApplicationGroupIdentifier:
                   @"YOUR_GROUP_STRING"];
    
    NSString *imagePath = [groupURL URLByAppendingPathComponent:@"Your_Shared_File_Name.jpg"].path;
    }
    
    if( [[NSFileManager defaultManager] fileExistsAtPath: imagePath]){
        image = [[UIImage alloc] initWithContentsOfFile: imagePath];
    }
    

On general I suggest you to use MMWormhole which can be used easily if you don't have any too complex things you need to pass between the Watch and the Host app.