无法在Chrome中获得共享扩展的价值

时间:2015-08-12 07:29:46

标签: ios objective-c iphone ios-extensions

我正在尝试建立一个在 Safari浏览器上正常运行的共享扩展程序,但它无法在 Chrome 浏览器上运行。

我还做了一些 RND ,发现我无法获取Chrome的值。

这是我的info.plist文件代码

<key>NSExtensionAttributes</key>
        <dict>
            <key>NSExtensionJavaScriptPreprocessingFile</key>
            <string>DemoPreprocessor</string>

            <key>NSExtensionActivationRule</key>
            <dict>
                <key>NSExtensionActivationSupportsText</key>
                <true/>
                <key>NSExtensionActiovationSupportsWebPageWithMaxCount</key>
                <integer>1</integer>
                <key>NSExtensionActivationSupportsWebURLWithMaxCount</key>
                <integer>1</integer>
            </dict>

允许显示我的Chrome和Safari浏览器的扩展程序。

这是我的DemoProcessor.js文件代码

var MyPreprocessor = function() {};
MyPreprocessor.prototype = {
    run: function(arguments) {
        arguments.completionFunction({"URL": document.URL, "pageSource": document.documentElement.outerHTML, "title": document.title, "selection": window.getSelection().toString()});
    }
};
var ExtensionPreprocessingJS = new NSItemProvider;

这是我的ShareViewcontroller.m代码

#import "ShareViewController.h"
#import "MBProgressHUD.h"

@import MobileCoreServices;

static NSString *const AppGroupId = @"group.tag.ssss7";

@implementation ShareViewController
{
    NSArray *arrayCategory;
    __weak IBOutlet UITextField *textFieldCategoryName;
    __weak IBOutlet UIButton *btnPost;
    __weak IBOutlet UIBarButtonItem *btnCancel;
    __weak IBOutlet UINavigationItem *nayTitle;
    __weak IBOutlet UINavigationBar *navBar;
}
-(void)viewDidLoad
{
    sharedUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:AppGroupId];
    [sharedUserDefaults setObject:@"hello" forKey:@"hello"];

    NSString *userId= [sharedUserDefaults objectForKey:@"userId"];

    NSLog(@"%@", [[sharedUserDefaults objectForKey:@"categories"] class]);
    NSError* error;
    [self didSelectPost];
    if (userId==nil || [userId isEqualToString:@""] )
    {
        [self hideBackground];
        self.view.hidden= YES;

        UIAlertController * alert=   [UIAlertController
                                      alertControllerWithTitle:@"Error"
                                      message:@"Please login into ssss"
                                      preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            [self hideExtentionView];

        }];

        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];

    }
    else
    {

    self.view.hidden= NO;

    id jsonObject = [NSJSONSerialization JSONObjectWithData:[sharedUserDefaults objectForKey:@"categories"] options: NSJSONReadingMutableContainers error:&error];
    arrayCategory= [NSArray arrayWithArray:jsonObject];
    NSLog(@"%@", [arrayCategory class]);

    NSMutableArray *cityArray = [[NSMutableArray alloc] init];
    NSMutableArray *testFeeds = [NSJSONSerialization JSONObjectWithData: [sharedUserDefaults objectForKey:@"categories"] options:NSJSONReadingMutableContainers error:nil];
    [cityArray addObjectsFromArray:testFeeds];
    NSLog(@"%lu", (unsigned long)[cityArray count]);

//    [self.tableViewssss reloadData];
    // here you must have to provide your app group id that you already created
}
}


-(void) hideBackground
{


    [self.view setBackgroundColor:[UIColor clearColor]];
    [self.tableViewssss setBackgroundColor:[UIColor clearColor]];
    [textFieldCategoryName setBackgroundColor:[UIColor clearColor]];
    [nayTitle setTitle:@""];
    [btnPost setHidden:YES];
    [navBar setHidden:YES];


}

- (BOOL)isContentValid {
    // Do validation of contentText and/or NSExtensionContext attachments here
    return YES;
}

- (void)didSelectPost {

    // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.

    // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.

    inputItem = self.extensionContext.inputItems.firstObject;
    NSItemProvider *urlItemProvider = [[inputItem.userInfo valueForKey:NSExtensionItemAttachmentsKey] objectAtIndex:0];

    if ([urlItemProvider hasItemConformingToTypeIdentifier:(__bridge NSString *)kUTTypeURL])
    {
        [urlItemProvider loadItemForTypeIdentifier:(__bridge NSString *)kUTTypeURL options:nil completionHandler:^(NSURL *url, NSError *error)
         {
             if (error)
             {
                 NSLog(@"Error occured");
             }
             else
             {
                 if ([sharedUserDefaults objectForKey:@"userId"]==nil)
                 {
                     UIAlertController * alert=   [UIAlertController
                                                   alertControllerWithTitle:@"Error"
                                                   message:@"You must be logged In to share"
                                                   preferredStyle:UIAlertControllerStyleAlert];

                     UIAlertAction* ok = [UIAlertAction
                                          actionWithTitle:@"OK"
                                          style:UIAlertActionStyleDefault
                                          handler:nil];

                     [alert addAction:ok];
                     [self presentViewController:alert animated:YES completion:nil];

                     return;

                 }


                 NSMutableArray *previousUrlsArray = [[NSMutableArray alloc]initWithArray:[sharedUserDefaults objectForKey:@"urlsArray"]];
                 if (previousUrlsArray==nil)
                 {
                     previousUrlsArray =[[NSMutableArray alloc]init];

                 }
                 [previousUrlsArray addObject:url.absoluteString];
                 NSMutableDictionary *dict= [[NSMutableDictionary alloc]init];
                 [dict setObject:previousUrlsArray forKey:@"urls"];
                 [sharedUserDefaults setObject:dict forKey:@"urlsDictionary"];

                 [sharedUserDefaults setObject:previousUrlsArray forKey:@"urlsArray"];
               //  [sharedUserDefaults synchronize];
                 [sharedUserDefaults setObject:url.absoluteString forKey:@"siteURL"];

                 [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@",url.absoluteString] forKey:@"sURL"];
                 NSLog(@"%@",[sharedUserDefaults objectForKey:@"sURL"]);

//                 NSMutableArray *arrSites;
//                 if ([sharedUserDefaults valueForKey:@"SharedExtension"])
//                     arrSites = [sharedUserDefaults valueForKey:@"SharedExtension"];
//                 else
//                     arrSites = [[NSMutableArray alloc] init];
//                 NSDictionary *dictSite = [NSDictionary dictionaryWithObjectsAndKeys:self.contentText, @"Text", url.absoluteString, @"URL",nil];
//                 [arrSites addObject:dictSite];
//                 [sharedUserDefaults setObject:arrSites forKey:@"SharedExtension"];
//                 [sharedUserDefaults synchronize];

//                 UIAlertController * alert=   [UIAlertController
//                                               alertControllerWithTitle:@"Success"
//                                               message:@"Posted Successfully."
//                                               preferredStyle:UIAlertControllerStyleAlert];
//                 
//                    UIAlertAction* ok = [UIAlertAction
//                                      actionWithTitle:@"OK"
//                                      style:UIAlertActionStyleDefault
//                                      handler:^(UIAlertAction * action)
//                                      {
//                                          [UIView animateWithDuration:0.20 animations:^
//                                           {
//                                               self.view.transform = CGAffineTransformMakeTranslation(0, self.view.frame.size.height);
//                                           }
//                                                           completion:^(BOOL finished)
//                                           {
//                                               [self.extensionContext completeRequestReturningItems:nil completionHandler:nil];
//                                           }];
//                                      }];
//                 
//                 [alert addAction:ok];
//                 [self presentViewController:alert animated:YES completion:nil];
             }
         }];
    }
}



- (NSArray *)configurationItems {
    // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
    return @[];
}

-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /*
         *   Actually create a new cell (with an identifier so that it can be dequeued).
         */

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] ;

        cell.selectionStyle = UITableViewCellSelectionStyleDefault;

    }
    cell.textLabel.text=[[arrayCategory objectAtIndex:indexPath.row] valueForKey:@"category_name"];
    return cell;
}


-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arrayCategory count];
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self saveInUserDefaultsWithCategoryName:[[arrayCategory objectAtIndex:indexPath.row] valueForKey:@"category_name"] andId:[[[arrayCategory objectAtIndex:indexPath.row] valueForKey:@"id"] integerValue]];

}
- (IBAction)postBtnTapped:(id)sender {

    [self saveInUserDefaultsWithCategoryName:textFieldCategoryName.text andId:-1];

}

-(void) saveInUserDefaultsWithCategoryName : (NSString*) categoryName andId : (NSInteger) categoryId
{







    NSString *stringId=[sharedUserDefaults objectForKey:@"id"];

    ([stringId length]>0) ? [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@,%ld",stringId, (long)categoryId] forKey:@"id"] : [sharedUserDefaults setObject:[NSString stringWithFormat:@"%ld", (long)categoryId] forKey:@"id"];
    NSLog(@"%@", [sharedUserDefaults objectForKey:@"id"]);

    NSString *stringCategoryName=[sharedUserDefaults objectForKey:@"category_name"];

    ([stringCategoryName length]>0) ? [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@,%@",stringCategoryName, categoryName] forKey:@"category_name"] : [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@",categoryName] forKey:@"category_name"];
    NSLog(@"%@", [sharedUserDefaults objectForKey:@"category_name"]);

    NSString *stringURL=[sharedUserDefaults objectForKey:@"URL"];

    ([stringURL length]>0) ? [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@,%@",stringURL, [sharedUserDefaults objectForKey:@"sURL"]] forKey:@"URL"] : [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@",[sharedUserDefaults objectForKey:@"sURL"]] forKey:@"URL"];
    NSLog(@"%@", [sharedUserDefaults objectForKey:@"URL"]);




    NSDictionary *categoryDictionary = [NSDictionary dictionaryWithObjectsAndKeys:categoryName,@"categoryName", nil];
    NSArray *categoryArray = [NSArray arrayWithObject:categoryDictionary];


    NSMutableDictionary *mainDictionary = [[NSMutableDictionary alloc]init];
    [mainDictionary setObject:categoryArray forKey:@"categories"];
    [mainDictionary setObject:@"0" forKey:@"categoryType"];
    [mainDictionary setObject:[sharedUserDefaults objectForKey:@"siteURL"] forKey:@"url"];
    [mainDictionary setObject:[sharedUserDefaults objectForKey:@"access_token"] forKey:@"access_token"];

    AppServices *appServices = [AppServices sharedInstance];
    appServices.delegate = self;
    [appServices postCategoriesOnServer:mainDictionary withSucessBlock:nil withfailureBlock:nil];

 UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Please choose hit a category or create a new one "
                                                                       message:@""
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:okAction];

        [self presentViewController:alert animated:YES completion:nil];


    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
   // [self enableUserInteraction:NO];
   // [[AppServices sharedInstance] sendData:nil withSucessBlock:nil withfailureBlock:nil];


//    [sharedUserDefaults setObject:[NSNumber numberWithInteger:categoryId] forKey:@"id"];
//    [sharedUserDefaults setObject:categoryName forKey:@"category_name"];




//    NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
//    
//    [dict setObject:categoryName forKey:@"category_name"];
//    [dict setObject:[NSNumber numberWithInteger:categoryId] forKey:@"id"];
//    NSLog(@"%@", [sharedUserDefaults objectForKey:@"siteURL"]);
//
//    [dict setObject:[sharedUserDefaults objectForKey:@"siteURL"] forKey:@"siteurl"];
//    
//    
//    [sharedUserDefaults setObject:[self dictToJson:dict] forKey:@"categorydictionary"];
}

-(NSString *)dictToJson:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dict
                                                       options:(NSJSONWritingOptions)  (/* DISABLES CODE */ (YES) ? NSJSONReadingMutableContainers : 0)
                                                         error:&error];

    if (! jsonData) {
        NSLog(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
        return @"{}";
    } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

}


- (IBAction)cancelBtnTapped:(id)sender {
    [self hideExtentionView];
}

-(void) hideExtentionView
{
    [self.extensionContext completeRequestReturningItems: nil completionHandler: nil];

}

-(void) showAlertViewWithMessage:(NSString *)message
{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [self hideExtentionView];

    }];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];

}

-(void)enableUserInteraction:(BOOL)enable
{
    [self.view setUserInteractionEnabled:enable];
}

#pragma mark- AppServicesDelegate methods
-(void)showMessage:(NSString *)message
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
  //  [self enableUserInteraction:YES];
    [self showAlertViewWithMessage:message];
}



@end

现在问题是On On代码,这个函数正在运行

  -(void) saveInUserDefaultsWithCategoryName : (NSString*) categoryName andId : (NSInteger) categoryId  {
**// not getting values for  chrome, but for Safari i am getting**

}

0 个答案:

没有答案