UIPastboard is not working in iOS 7?

2019-09-08 17:46发布

问题:

I am working on a iOS application in which I have to share some data between two applications and I am using UIPastboard and data is sharing successfully in iOS below 7.0 but not working in iOS 7. Here is the code I am using:

// Code for writing .... Used in application "A"

NSString * name = @"peter";
NSNumber *age = [NSNumber numberWithInteger:[@"33" integerValue]];

NSMutableDictionary * dict =[[NSMutableDictionary alloc]init];
[dict setObject:name forKey:@"name"];
[dict setObject:age forKey:@"age"];

UIPasteboard * pb = [UIPasteboard pasteboardWithName:@"mypasteboard" create:YES];
[pb setPersistent:YES];
[pb setData:[NSKeyedArchiver archivedDataWithRootObject:dict] forPasteboardType:@"mydata"];

//Code for reading..... Used in application "B"

 UIPasteboard * pb=[UIPasteboard pasteboardWithName:@"mypasteboard" create:NO];
    NSData * data=[[NSData alloc] init];


    data=[pb valueForPasteboardType:@"mydata"];
    NSDictionary * dict;

    if (!data) {
        return nil;
    }
    @try {
        dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    @catch (NSException* exception)
    {
        NSLog(@"Exception: %@",exception);
        return nil;
    }


         if(dict)  //In iOS 7 dict contains 'nil' but not in iOS 6.
       {
           NSString * name = [dict objectForKey:@"name"];
           NSNumber * age = [dict objectForKey:@"age"];
           message =[NSString stringWithFormat:@"name =%@,\nage=%@",name,age];
       }
       else
       {
           message =@"No data from Pasteboard";
       }


        UIAlertView *alertView2 = [[UIAlertView alloc] initWithTitle:@"Pasteboard Data"
                                                             message:message
                                                            delegate:self
                                                   cancelButtonTitle:@"Ok"
                                                   otherButtonTitles:Nil, nil];

        alertView2.alertViewStyle = UIAlertViewStyleDefault;
        [alertView2 show];

In iOS 7 dict contains 'nil' but in iOS 6 contains data which is set in application 'A'.

Please suggest me any solution for this issue.

回答1:

Try this,

UIPasteboard * pb = [UIPasteboard pasteboardWithName:@"mypasteboard" create:YES];
[pb setPersistent:YES];
[pb setValue:[NSKeyedArchiver archivedDataWithRootObject:dict] forPasteboardType:@"mydata"];