Не удалось запустить bms-samples-cordova-hellopush — файл bms_samples_cordova_push-Swift.h не найден

Я пытаюсь запустить образец push-уведомлений, доступный на GitHub. К сожалению, конфигурация описана здесь не работает.

Документы говорят: В верхней части вашего AppDelegate.m:

#import "[your-project-name]-Swift.h"

Если в имени вашего проекта есть пробелы или дефисы, замените их символами подчеркивания в операторе импорта.

Пример:

// Project name is "Test Project" or "Test-Project"
#import "Test_Project-Swift.h"

Так я сделал для образца:

#import "bms_samples_cordova_push-Swift.h"

Заголовок моста ObjC установлен на:

bms-samples-cordova-push/Plugins/ibm-mfp-core/Bridging-Header.h

Путь выполнения установлен на:

@executable_path/Frameworks

Но Xcode выдает ошибку выше. Что я делаю неправильно?


person Sebastian    schedule 07.07.2016    source источник


Ответы (1)


Мне удалось запустить пример приложения bms-samples-cordova-hellopush, выполнив следующие действия:

  1. Клонировал образец:

    git clone https://github.com/ibm-bluemix-mobile-services/bms-samples-cordova-hellopush

  2. Добавлен мой APPLICATION_ROUTE и APPLICATION_GUID в мой [your-directory]/www/js/index.js (после настройки push-уведомлений для моего приложения Mobile Services Starter в Bluemix

  3. Добавил платформу iOS в мое приложение:

    cordova platform add [email protected]

  4. Добавлен плагин Cordova:

    cordova plugin add ibm-mfp-push

  5. Открыл мой файл [your-app-name].xcodeproj в моем каталоге [your-app-name]/platforms/ios с помощью Xcode (когда мне было предложено: Преобразовать в последний синтаксис Swift, я нажал Отмена)

  6. Добавлен связующий заголовок. Перешел на Build settings > Swift Compiler - Code Generation > Objective-C Bridging Header и добавил следующий путь:

    [your-project-name]/Plugins/ibm-mfp-core/Bridging-Header.h

между заголовками

  1. Добавьте параметр Frameworks. Перешел на Build Settings > Linking > Runpath Search Paths и добавил следующий параметр:

    @executable_path/Frameworks

путь к исполняемому файлу

  1. Построенный проект

  2. Раскомментировал следующие операторы импорта Push в моем связующем заголовке. Пошел к [your-project-name]/Plugins/ibm-mfp-core/Bridging-Header.h:

между заголовками

  1. Мое клиентское приложение обновлено для использования Push SDK.

Вот мой обновленный AppDelegate.m:

/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

//
//  AppDelegate.m
//  bms-samples-cordova-push
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//  Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"
#import "bms_samples_cordova_push-Swift.h"


#import <Cordova/CDVPlugin.h>

@implementation AppDelegate

@synthesize window, viewController;

- (id)init
{
    /** If you need to do any extra app-specific initialization, you can do it here
     *  -jm
     **/
    NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

    int cacheSizeMemory = 8 * 1024 * 1024; // 8MB
    int cacheSizeDisk = 32 * 1024 * 1024; // 32MB
#if __has_feature(objc_arc)
        NSURLCache* sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
#else
        NSURLCache* sharedCache = [[[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"] autorelease];
#endif
    [NSURLCache setSharedURLCache:sharedCache];

    self = [super init];
    return self;
}

#pragma mark UIApplicationDelegate implementation

/**
 * This is main kick off after the app inits, the views and Settings are setup here. (preferred - iOS4 and up)
 */
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    CGRect screenBounds = [[UIScreen mainScreen] bounds];

#if __has_feature(objc_arc)
        self.window = [[UIWindow alloc] initWithFrame:screenBounds];
#else
        self.window = [[[UIWindow alloc] initWithFrame:screenBounds] autorelease];
#endif
    self.window.autoresizesSubviews = YES;

#if __has_feature(objc_arc)
        self.viewController = [[MainViewController alloc] init];
#else
        self.viewController = [[[MainViewController alloc] init] autorelease];
#endif

    // Set your app's start page by setting the <content src='foo.html' /> tag in config.xml.
    // If necessary, uncomment the line below to override it.
    // self.viewController.startPage = @"index.html";

    // NOTE: To customize the view's frame size (which defaults to full screen), override
    // [self.viewController viewWillAppear:] in your view controller.

    [[CDVMFPPush sharedInstance] didReceiveRemoteNotificationOnLaunch:launchOptions];

    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

    return YES;
}

// this happens while we are running ( in the background, or from within our own app )
// only valid if bms-samples-cordova-push-Info.plist specifies a protocol to handle
- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
{
    if (!url) {
        return NO;
    }

    // all plugins will get the notification, and their handlers will be called
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];

    return YES;
}

// repost all remote and local notification using the default NSNotificationCenter so multiple plugins may respond
- (void)            application:(UIApplication*)application
    didReceiveLocalNotification:(UILocalNotification*)notification
{
    // re-post ( broadcast )
    [[NSNotificationCenter defaultCenter] postNotificationName:CDVLocalNotification object:notification];
}


#if __IPHONE_OS_VERSION_MAX_ALLOWED < 90000
- (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
#else
- (UIInterfaceOrientationMask)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
#endif
{
    // iPhone doesn't support upside down by default, while the iPad does.  Override to allow all orientations always, and let the root view controller decide what's allowed (the supported orientations mask gets intersected).
    NSUInteger supportedInterfaceOrientations = (1 << UIInterfaceOrientationPortrait) | (1 << UIInterfaceOrientationLandscapeLeft) | (1 << UIInterfaceOrientationLandscapeRight) | (1 << UIInterfaceOrientationPortraitUpsideDown);

    return supportedInterfaceOrientations;
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application
{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

// Register device token with Bluemix Push Notification Service
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    [[CDVMFPPush sharedInstance] didRegisterForRemoteNotifications:deviceToken];
}

// Handle error when failed to register device token with APNs
- (void)application:(UIApplication*)application
didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {
    
    [[CDVMFPPush sharedInstance] didFailToRegisterForRemoteNotifications:error];
}

// Handle receiving a remote notification
-(void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [[CDVMFPPush sharedInstance] didReceiveRemoteNotification:userInfo];
}

@end
  1. Запустите образец на устройстве iOS, чтобы зарегистрироваться и получать push-уведомления.

Надеюсь ничего не пропустил :0)

Я связался с командой Cordova и сообщил о нескольких проблемах, чтобы улучшить качество этого образца и упростить его настройку.

Редактировать: Кроме того, как отметил Себастьян ниже, вам необходимо отключить биткод.

person joe    schedule 07.07.2016
comment
Если бы я следовал этим шагам точно по порядку, это сработало. Кроме того, мне пришлось отключить биткод и создать новый экземпляр службы push-уведомлений, потому что он выдавал ошибки HTTP 500. Большое спасибо - person Sebastian; 08.07.2016