0

I use Multi-Peer Connectivity framework's –

sendResourceAtURL:withName:toPeer:withCompletionHandler:

method to send image.But I find a problem:if the image sending isn't finished and I call MCSession's disconnect method,the app crashes.So I want to know how to safely stop sending image with Multi-Peer Connectivity.

    - (Transcript *)sendImage:(NSURL *)imageUrl
{
    NSProgress *progress;
    // Loop on connected peers and send the image to each
    for (MCPeerID *peerID in self.MySession.connectedPeers) {
        // Send the resource to the remote peer.  The completion handler block will be called at the end of sending or if any errors occur
        progress = [self.MySession sendResourceAtURL:imageUrl withName:[NSString stringWithFormat:@"%@!@#%@",[imageUrl lastPathComponent],self.MyUserName] toPeer:peerID withCompletionHandler:^(NSError *error) {
            // Implement this block to know when the sending resource transfer completes and if there is an error.
            if (error) {
                NSLog(@"Send resource to peer [%@] completed with Error [%@]", peerID.displayName, error);
            }
            else {
                // Create an image transcript for this received image resource
                Transcript *transcript = [[Transcript alloc] initWithUserName:self.MyUserName imageUrl:imageUrl direction:TRANSCRIPT_DIRECTION_SEND];
                [self.delegate updateTranscript:transcript];
            }
        }];
    }
    // Create an outgoing progress transcript.  For simplicity we will monitor a single NSProgress.  However users can measure each NSProgress returned individually as needed
    Transcript *transcript = [[Transcript alloc] initWithUserName:self.MyUserName imageName:[imageUrl lastPathComponent] progress:progress direction:TRANSCRIPT_DIRECTION_SEND];

    return transcript;
}
Han Pengbo
  • 1,338
  • 1
  • 18
  • 37
  • Can you post some code? What's in your completion block? – ChrisH May 14 '14 at 17:16
  • @ChrisH I create a new instance of custom class and call a custom delegate instant's method. – Han Pengbo May 16 '14 at 03:40
  • My guess would be the references to self in the completion block. http://stackoverflow.com/questions/4352561/retain-cycle-on-self-with-blocks – ChrisH May 17 '14 at 00:34
  • @ChrisH I use __weak id weakDelegate = self.delegate;But the problem still exist. – Han Pengbo May 19 '14 at 02:23
  • It's not just the delegate reference. You've got several explicit references to `self` in that block along with an implicit reference with your `progress` ivar. You need `__weak id weakSelf = self` – ChrisH May 20 '14 at 01:25

1 Answers1

1

You must set one BOOL variable or notification on your image sending completionHandler than check whenever you get that BOOL value correct or that notification, if it is correct than you can call MCSession's disconnect method.

iMSaM
  • 118
  • 5