1

要求: 我们能够从主机设备连接到多个从设备。例如,如果设备 A 向设备 B 和 C 发起连接,则贡献者设备可以接受对等连接并连接到设备 A。这里 A 是主设备,B 和 C 是贡献者设备。现在如果 B 将他们的歌曲分享给 A,A 就可以播放歌曲并查看歌曲信息。与此同时,C 将处于空闲状态,但应该连接。当 B 播放完歌曲后, C 也可以将自己的歌曲分享到设备 A。

以下是我们在完成上述任务时遇到的问题: 1. B 开始向 A 分享歌曲时,C 就崩溃了。但是 A 仍然可以播放 B 共享的歌曲。

array = [[NSMutableArray alloc] initWithObjects:[self.session connectedPeers], nil];
[_session sendData:[NSKeyedArchiver archivedDataWithRootObject:[info mutableCopy]]  toPeers:[array objectAtIndex:0] withMode:MCSessionSendDataUnreliable error: &error];
NSLog(@"localizedDescription %@",error);    
  1. 为了克服这个问题,直接在这里传递没有索引的数组toPeers:array。它正在工作,我们能够与设备 A 共享和播放歌曲,但设备 A 无法接收歌曲信息。

以下是我们正在使用的完整代码:贡献者控制器:

    - (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
    [self dismissViewControllerAnimated:YES completion:nil];
    someMutableArray = [mediaItemCollection items];
        counter = 0;
    if(someMutableArray.count>1){
        BOOL isselectsongone=YES;
        [[NSUserDefaults standardUserDefaults] setBool:isselectsongone forKey:@"isselectsongone"];
    }
    [self showSpinner];
        [self someSelector:nil];


     }

- (void)someSelector:(NSNotification *)notification {
    if(notification && someMutableArray.count>1 && counter <someMutableArray.count-1){
        NSDate *start = [NSDate date];

        counter=counter+1;
         [self.outputStreamer stop];
         self.outputStreamer = nil;
         self.outputStream = nil;

    }
        song=[someMutableArray objectAtIndex:counter];
    NSMutableDictionary *info = [NSMutableDictionary dictionary];

    info=[[NSMutableDictionary alloc] init];
    info[@"title"] = [song valueForProperty:MPMediaItemPropertyTitle] ? [song valueForProperty:MPMediaItemPropertyTitle] : @"";
    info[@"artist"] = [song valueForProperty:MPMediaItemPropertyArtist] ? [song valueForProperty:MPMediaItemPropertyArtist] : @"";
    //NSNumber *duration=[song valueForProperty:MPMediaItemPropertyPlaybackDuration];

    int fullminutes = floor([timeinterval floatValue] / 60); // fullminutes is an int
    int fullseconds = trunc([duration floatValue] - fullminutes * 60);  // fullseconds is an int

    [NSTimer scheduledTimerWithTimeInterval:[duration doubleValue]target:self selector:@selector(getdata) userInfo:nil repeats:YES];

   }

-(void)getdata {
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    info=[[NSMutableDictionary alloc] init];
    info[@"title"] = [song valueForProperty:MPMediaItemPropertyTitle] ? [song valueForProperty:MPMediaItemPropertyTitle] : @"";
    info[@"artist"] = [song valueForProperty:MPMediaItemPropertyArtist] ? [song valueForProperty:MPMediaItemPropertyArtist] : @"";
    NSNumber *duration=[song valueForProperty:MPMediaItemPropertyPlaybackDuration];

    int fullminutes = floor([duration floatValue] / 60); // fullminutes is an int
    int fullseconds = trunc([duration floatValue] - fullminutes * 60);  // fullseconds is an int

    info[@"duration"] = [NSString stringWithFormat:@"%d:%d", fullminutes, fullseconds];

    MPMediaItemArtwork *artwork = [song valueForProperty:MPMediaItemPropertyArtwork];

    UIImage *image = [artwork imageWithSize:CGSizeMake(150, 150)];
    NSData * data = UIImageJPEGRepresentation(image, 0.0);
    image = [UIImage imageWithData:data];



    array = [[NSMutableArray alloc] initWithObjects:[self.session connectedPeers], nil];
    MCPeerID* peerID11 = self.session.myPeerID;
    NSMutableArray *arr=[[NSMutableArray alloc] initWithObjects:peerID11, nil];
    NSLog(@"%@",arr);
    if (image)
        self.songArtWorkImageView.image = image;
    else
        self.songArtWorkImageView.image = nil;

    self.songTitleLbl.text = [NSString stringWithFormat:@"%@ \n[Artist : %@]", info[@"title"], info[@"artist"]];

    NSError *error;

    [_session sendData:[NSKeyedArchiver archivedDataWithRootObject:[info mutableCopy]]  toPeers:[array objectAtIndex:0] withMode:MCSessionSendDataUnreliable error: &error];
    NSLog(@"localizedDescription %@",error);



    @try {
        if(_session && _session.connectedPeers && [_session.connectedPeers count] > 0)   {

            NSLog(@"%@",[song valueForProperty:MPMediaItemPropertyAssetURL]);
                    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[song valueForProperty:MPMediaItemPropertyAssetURL] options:nil];

                    [self convertAsset: asset complition:^(BOOL Success, NSString *filePath) {
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                            if(Success) {

                                                              if(image)   {
                                    [self saveImage: image withComplition:^(BOOL status, NSString *imageName, NSURL *imageURL) {
                                        if(status)  {
                                            @try {

                                                [_session sendResourceAtURL:imageURL withName:imageName toPeer:[_session.connectedPeers objectAtIndex:0]withCompletionHandler:^(NSError *error) {
                                                    if (error) {
                                                        NSLog(@"Failed to send picture to %@", error.localizedDescription);
                                                        return;
                                                    }
                                                    //Clean up the temp file
                                                    NSFileManager *fileManager = [NSFileManager defaultManager];
                                                    [fileManager removeItemAtURL:imageURL error:nil];
                                                }];

                                            }
                                            @catch (NSException *exception) {

                                            }
                                        }
                                    }];
                                }
                                              @try {
                                                   [self hideSpinner];
                                    if(!self.outputStream)  {
                                        NSArray * connnectedPeers = [_session connectedPeers];
                                        if([connnectedPeers count] != 0)    {
                                            [self outputStreamForPeer:[_session.connectedPeers objectAtIndex:0]];
                                        }
                                    }
                                }
                                @catch (NSException *exception) {

                                }
                                if(self.outputStream)    {

                                        self.outputStreamer = [[TDAudioOutputStreamer alloc] initWithOutputStream:self.outputStream];
//
                                    [self.outputStreamer initStream:filePath];
                                    NSLog(@"%@",filePath);
                                    if(self.outputStreamer)    {
                                    [self.outputStreamer start];

                                    }

                                    else{
                                        NSLog(@"Error: output streamer not found");

                                    }

                                }
                                else{
                                    //self.outputStream=[[NSOutputStream alloc] init];
                                    self.outputStreamer = [[TDAudioOutputStreamer alloc] initWithOutputStream:self.outputStream];
                                    [self.outputStreamer initStream:filePath];
                                    NSLog(@"%@",filePath);
                                    if(self.outputStreamer)    {

                                        [self.outputStreamer start];

                                    }


                                }

                            }
                            else    {
                                [UIView showMessageWithTitle:@"Error!" message:@"Error occured!" showInterval:1.5];
                            }


                        });
                    }];

              // }

        }
    }

    @catch (NSException *exception) {
        NSLog(@"Expection: %@", [exception debugDescription]);
    }
//}
}

主机视图控制器:

    - (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID
{

    NSLog(@"%@",peerID);
    NSLog(@"sessions%@",session);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        @try {
        // NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:data];
           info = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            self.songTitleLbl.text = [NSString stringWithFormat:@"%@ \n[Duration: %@] [Artist : %@] ", info[@"title"], info[@"duration"], info[@"artist"]];
            NSLog(@"eeret%@",self.songTitleLbl.text);
            self.songArtWorkImageView.image = nil;
            [self showSpinner];
        }
        @catch (NSException *exception) {
            self.songTitleLbl.text = @"Some error occured...\nPlease try again";
            self.songArtWorkImageView.image = nil;
        }
    });
}

如果我在这里遗漏了什么或实现上述要求的更好方法,请告诉我们。任何帮助都非常感谢。

4

0 回答 0