From Swift to Objective-C?

145 views Asked by At

I'm trying to implement deep linking in my iOS app (which I 'made' in Cocos Creator), and I want to implement this functionality

func application(_ application: UIApplication,
                 open url: URL,
                 options: [UIApplicationOpenURLOptionsKey : Any] = [:] ) -> Bool {

    // Determine who sent the URL.
    let sendingAppID = options[.sourceApplication]
    print("source application = \(sendingAppID ?? "Unknown")")

    // Process the URL.
    guard let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true),
        let albumPath = components.path,
        let params = components.queryItems else {
            print("Invalid URL or album path missing")
            return false
    }

    if let photoIndex = params.first(where: { $0.name == "index" })?.value {
        print("albumPath = \(albumPath)")
        print("photoIndex = \(photoIndex)")
        return true
    } else {
        print("Photo index missing")
        return false
    }
}

... which is Swift code (?) and from here

https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app

in my AppController.mm

/****************************************************************************
 Copyright (c) 2010-2013 cocos2d-x.org
 Copyright (c) 2013-2016 Chukong Technologies Inc.
 Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
 
 http://www.cocos2d-x.org
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

#import "AppController.h"
#import "cocos2d.h"
#import "AppDelegate.h"
#import "RootViewController.h"
#import "SDKWrapper.h"
#import "platform/ios/CCEAGLView-ios.h"



using namespace cocos2d;

@implementation AppController

Application* app = nullptr;
@synthesize window;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[SDKWrapper getInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    // Add the view controller's view to the window and display.
    float scale = [[UIScreen mainScreen] scale];
    CGRect bounds = [[UIScreen mainScreen] bounds];
    window = [[UIWindow alloc] initWithFrame: bounds];
    
    // cocos2d application instance
    app = new AppDelegate(bounds.size.width * scale, bounds.size.height * scale);
    app->setMultitouch(true);
    
    // Use RootViewController to manage CCEAGLView
    _viewController = [[RootViewController alloc]init];
#ifdef NSFoundationVersionNumber_iOS_7_0
    _viewController.automaticallyAdjustsScrollViewInsets = NO;
    _viewController.extendedLayoutIncludesOpaqueBars = NO;
    _viewController.edgesForExtendedLayout = UIRectEdgeAll;
#else
    _viewController.wantsFullScreenLayout = YES;
#endif
    // Set RootViewController to window
    if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)
    {
        // warning: addSubView doesn't work on iOS6
        [window addSubview: _viewController.view];
    }
    else
    {
        // use this method on ios6
        [window setRootViewController:_viewController];
    }
    
    [window makeKeyAndVisible];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
    //run the cocos2d-x game scene
    app->start();
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
    app->onPause();
    [[SDKWrapper getInstance] applicationWillResignActive:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    app->onResume();
    [[SDKWrapper getInstance] applicationDidBecomeActive:application];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
    [[SDKWrapper getInstance] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
    [[SDKWrapper getInstance] applicationWillEnterForeground:application];    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    [[SDKWrapper getInstance] applicationWillTerminate:application];
    delete app;
    app = nil;
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}

@end

... which is an Objective-C file?

Any ideas on how to achieve that would be fantastic! Thank you!

1

There are 1 answers

3
Shawn Frank On

If I understood you right, I believe your question is to convert the above Swift function into Objective C

You can give this a go and see if it helps:

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    
    id sendingAppID
    = [options objectForKey: UIApplicationOpenURLOptionsSourceApplicationKey];
    
    if (sendingAppID) {
        NSLog(@"source application = %@", sendingAppID);
    }
    
    NSURLComponents *components
    = [[NSURLComponents alloc] initWithURL: url resolvingAgainstBaseURL: YES];
    
    NSString *albumPath = components.path;
    
    NSArray *params = components.queryItems;
    
    if (!components && !albumPath && !params) {
        NSLog(@"Invalid URL or album path missing");
        return NO;
    }
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"name = index"];
    NSArray *filteredArray = [params filteredArrayUsingPredicate: predicate];
    
    if ([filteredArray firstObject]) {
        
        NSURLQueryItem *queryItem = [filteredArray firstObject];
        NSString *photoIndex = queryItem.value;
        
        NSLog(@"albumPath = %@", albumPath);
        NSLog(@"photoIndex = %@", photoIndex);
        return YES;
    }
    
    NSLog(@"Photo index missing");
    return NO;
}

The bit I am not too sure about is the predicate bit which is supposed to replace the filter in Swift.

Let me know if this worked or not.

Update based on Willeke's recommendation

As suggested by Willeke in the comments, using indexOfObjectPassingTest: is better than using the predicate.

I believe this is how you would update the code

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    
    id sendingAppID
    = [options objectForKey: UIApplicationOpenURLOptionsSourceApplicationKey];
    
    if (sendingAppID) {
        NSLog(@"source application = %@", sendingAppID);
    }
    
    NSURLComponents *components
    = [[NSURLComponents alloc] initWithURL: url resolvingAgainstBaseURL: YES];
    
    NSString *albumPath = components.path;
    
    NSArray *params = components.queryItems;
    
    if (!components && !albumPath && !params) {
        NSLog(@"Invalid URL or album path missing");
        return NO;
    }
    
    NSUInteger photoIndex = [params indexOfObjectPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSURLQueryItem *queryItem = (NSURLQueryItem*) obj;
        return [queryItem.name isEqual: @"index"];
    }];
    
    if (photoIndex != NSNotFound) {
        
        NSURLQueryItem *queryItem = [params objectAtIndex: photoIndex];
        NSString *photoIndex = queryItem.value;
        
        NSLog(@"albumPath = %@", albumPath);
        NSLog(@"photoIndex = %@", photoIndex);
        return YES;
        
    }
    
    NSLog(@"Photo index missing");
    return NO;
}