使用Python编写iOS原生应用的框架设计思考(首篇二)

简介: 使用Python编写iOS原生应用的框架设计思考(首篇)

三、编写桥接文件


     这部分主要有Objective-C实现,用来启动Python引擎,加载Python业务代码的入口文件,做各种原生组件与Python组件的桥接等。首先编写一个头文件用来进行静态变量和宏的定义,如下:


//

//  BrdgeDefine.h

//  PyNativeDemo

//

//  Created by 珲少 on 2020/4/30.

//  Copyright © 2020 jaki. All rights reserved.

//


#ifndef BrdgeDefine_h

#define BrdgeDefine_h

#import <Python/Python.h>


#define INTERFACE_INSTANCE + (instancetype)sharedInstance;


#define IMPLEMENTATION_INSTANCE             \

+ (instancetype)sharedInstance {            \

   static id instance = nil;               \

   static dispatch_once_t onceToken;       \

   dispatch_once(&onceToken, ^{            \

       if (!instance) {                    \

           instance = [[self alloc] init]; \

       }                                   \

   });                                     \

   return instance;                        \

}


#define SELF_INSTANCE [self.class sharedInstance]



#endif /* BrdgeDefine_h */

编写Python桥的引擎类,如下:


BridgeEnigine.h:


#import <Foundation/Foundation.h>

#import "BrdgeDefine.h"

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN


@interface BridgeEngine : NSObject


INTERFACE_INSTANCE


+ (UIViewController *)setupEngine;


@end


NS_ASSUME_NONNULL_END

BridgeEnigine.m:


#import "BridgeEngine.h"

#import "DisplayRender.h"

#import "PythonRun.h"


@interface BridgeEngine ()


@end


@implementation BridgeEngine


IMPLEMENTATION_INSTANCE


+ (UIViewController *)setupEngine {

   [SELF_INSTANCE startEngine];

   [SELF_INSTANCE loadLib];

   [SELF_INSTANCE runMain];

   return [SELF_INSTANCE renderRoot];

}


- (void)startEngine {

   NSString* frameworkPath = [NSString stringWithFormat:@"%@/Resources",[SELF_INSTANCE p_pythonFrameworkPath]];

   wchar_t *pythonHome = [SELF_INSTANCE stingTowWchar_t:frameworkPath];

   Py_SetPythonHome(pythonHome);

   Py_Initialize();

   PyEval_InitThreads();

   if (Py_IsInitialized()) {

       NSLog(@"😄初始化环境成功😄");

   } else {

       NSLog(@"😢Python初始化环境失败😢");

       exit(0);

   }

}


- (void)loadLib {

   NSString *path = [NSString stringWithFormat:@"import sys\nsys.path.append(\"%@\")",[[NSBundle mainBundle] resourcePath]];

   PyRun_SimpleString([path UTF8String]);

   NSLog(@"😄lib加载成功😄");

}


- (void)runMain {

   PyObject * pModule = PyImport_ImportModule([@"main" UTF8String]);//导入模块

   [PythonRun sharedInstance].mainItemDic = PyModule_GetDict(pModule);

}


- (UIViewController *)renderRoot {

   return [[DisplayRender sharedInstance] renderRoot:@"Main"];

}


- (wchar_t *)stingTowWchar_t:(NSString*)string {

   return (wchar_t*)[string cStringUsingEncoding:NSUTF32StringEncoding];

}


- (NSString*)p_pythonFrameworkPath{

   NSString* path = [[NSBundle mainBundle] pathForResource:@"Python" ofType:@"framework"];

   return path;

}


- (void)dealloc {

   Py_Finalize();

}


@end

其中有使用到DisplayRender,由于Python没有办法主动调用原生,初步设想,让这个类通过帧刷新来负责对界面的渲染维护,编码如下:


DisplayRender.h:


#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

#import "BrdgeDefine.h"


NS_ASSUME_NONNULL_BEGIN


@interface DisplayRender : NSObject


INTERFACE_INSTANCE


- (UIViewController *)renderRoot:(NSString *)main;


@end


NS_ASSUME_NONNULL_END

DisplayRender.m:


#import "DisplayRender.h"

#import "PythonRun.h"

#import "BridgeColor.h"

#import "ViewMaker.h"


@interface DisplayRender ()


@property (nonatomic, strong) UIViewController *rootController;


@property (nonatomic, strong) NSMutableArray<UIView *> *subViews;


@end


@implementation DisplayRender


IMPLEMENTATION_INSTANCE


- (UIViewController *)renderRoot:(NSString *)main {

   NSDictionary *root = [[PythonRun sharedInstance] run:[main UTF8String] method:[@"render_main_view" UTF8String]];

   NSLog(@"AppLaunchFinish🙅‍♀️");

   [self renderController:root];

   return self.rootController;

}


- (void)renderController:(NSDictionary *)info {

   [self.subViews enumerateObjectsUsingBlock:^(UIView *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

       [obj removeFromSuperview];

   }];

   [self.subViews removeAllObjects];

 

   NSString *bg = [info objectForKey:@"color"];

   self.rootController.view.backgroundColor = [BridgeColor colorWith:bg];

   NSArray *views = [info objectForKey:@"subViews"];

   for (NSUInteger i = 0; i < views.count; i++) {

       id view = [ViewMaker makerView:[views[i] objectForKey:@"name"]];

       for (NSString *key in [views[i] allKeys]) {

           if (![key isEqualToString:@"name"]) {

               [view setValue:[views[i] objectForKey:key] forKey:key];

           }

       }

       [self.subViews addObject:view];

       [self.rootController.view addSubview:view];

   }

}


- (UIViewController *)rootController {

   if (!_rootController) {

       _rootController = [[UIViewController alloc] init];

   }

   return _rootController;

}


@end

PythonRun是一个工具类,起来调用Python解释器对Python代码进行执行,并通过数据与原生端进行交互,编码如下:


PythonRun.h:


#import <Foundation/Foundation.h>

#import "BrdgeDefine.h"


NS_ASSUME_NONNULL_BEGIN


@interface PythonRun : NSObject


INTERFACE_INSTANCE


@property (nonatomic, assign) PyObject *mainItemDic;


- (NSDictionary *)run:(const char *)item method:(const char *)method;


@end


NS_ASSUME_NONNULL_END

PythonRun.m:


#import "PythonRun.h"


@implementation PythonRun


IMPLEMENTATION_INSTANCE


- (NSDictionary *)run:(const char *)item method:(const char *)method {

   PyObject* pClassCalc = PyDict_GetItemString(self.mainItemDic,item);

   PyObject* pInstanceCalc = PyInstanceMethod_New(pClassCalc);

   PyObject* pRet = PyObject_CallMethod(pClassCalc, method, "O", pInstanceCalc);

   return [self dumpInfo:pRet];

}


- (NSDictionary *)dumpInfo:(PyObject *)pRet {

   // 解析数据

   char * resultCString = NULL;

   PyArg_Parse(pRet, "s", &resultCString);

   //将python类型的返回值转换为c

   return [self dumpString:resultCString];

}


- (NSDictionary *)dumpString:(const char *)resultCString {

   NSString *jsonString = [NSString stringWithCString:resultCString encoding:NSUTF8StringEncoding];

   NSDictionary *info = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];

   NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:info];

   for (NSString *k in dic.allKeys) {

       if ([k isEqualToString:@"subViews"]) {

           NSMutableArray *array = [NSMutableArray array];

           for (NSUInteger i = 0; i < [dic[k] count]; i++) {

                 [array addObject:[self dumpString:[dic[k][i] UTF8String]]];

           }

           dic[k] = [array copy];

       }

   }

   NSLog(@"dumpInfo❄️:%@", dic);

   return [dic copy];

}


@end

通过上面3个核心类,一个简易的Python引擎就完整了,下面还需要编写几个转换类,用来将Python对象转换成Objective-C的对象,编写BridgeColor类如下:


BridgeColor.h:


#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>


NS_ASSUME_NONNULL_BEGIN


@interface BridgeColor : NSObject


+ (UIColor *)colorWith:(NSString *)c;


@end


NS_ASSUME_NONNULL_END

BridgeColor.m:


#import "BridgeColor.h"



@implementation BridgeColor


+ (UIColor *)colorWith:(NSString *)c {

   if ([c isEqualToString:@"red"]) {

       return [UIColor redColor];

   } else if ([c isEqualToString:@"white"]) {

       return [UIColor whiteColor];

   } else if ([c isEqualToString:@"purple"]) {

       return [UIColor purpleColor];

   }

   return [UIColor clearColor];

}


@end

BridgeLabel.h:


#import <UIKit/UIKit.h>


NS_ASSUME_NONNULL_BEGIN


@interface BridgeLabel : UILabel


@property (nonatomic, strong) NSNumber *left;

@property (nonatomic, strong) NSNumber *top;

@property (nonatomic, strong) NSNumber *width;

@property (nonatomic, strong) NSNumber *height;

@property (nonatomic, strong) NSNumber *font_size;


@property (nonatomic, copy) NSString *background_color;

@property (nonatomic, copy) NSString *t;

@property (nonatomic, copy) NSString *color;


@end


NS_ASSUME_NONNULL_END

BridgeLabel.m:


#import "BridgeLabel.h"

#import "BridgeColor.h"


@implementation BridgeLabel


- (void)setLeft:(NSNumber *)left {

   _left = left;

   self.frame = CGRectMake(left.floatValue, self.frame.origin.y, self.frame.size.width, self.frame.size.height);

}


- (void)setTop:(NSNumber *)top {

   _top = top;

   self.frame = CGRectMake(self.frame.origin.x, top.floatValue, self.frame.size.width, self.frame.size.height);

}


- (void)setWidth:(NSNumber *)width {

   _width = width;

   self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, width.floatValue, self.frame.size.height);

}


- (void)setHeight:(NSNumber *)height {

   _height = height;

   self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, height.floatValue);

}


- (void)setColor:(NSString *)color {

   _color = color;

   self.textColor = [BridgeColor colorWith:color];

}


- (void)setT:(NSString *)t {

   _t = t;

   self.text = t;

}


- (void)setFont_size:(NSNumber *)font_size {

   _font_size = font_size;

   self.font = [UIFont systemFontOfSize:font_size.intValue];

}


- (void)setBackground_color:(NSString *)background_color {

   _background_color = background_color;

   self.backgroundColor = [BridgeColor colorWith:background_color];

}


@end

ViewMaker.h:


#import <Foundation/Foundation.h>


NS_ASSUME_NONNULL_BEGIN


@interface ViewMaker : NSObject


+ (id)makerView:(NSString *)name;


@end


NS_ASSUME_NONNULL_END

ViewMaker.m:


#import "ViewMaker.h"

#import "BridgeLabel.h"


@implementation ViewMaker


+ (id)makerView:(NSString *)name {

   if ([name isEqualToString:@"Label"]) {

       return [[BridgeLabel alloc] init];

   }

   return nil;

}


@end

四、编写Python业务代码


     在项目中添加两个Python文件,一个命名为main.py作为应用程序的入口文件,一个命名为label.py作为标签组件,main.py文件编写代码如下:


import json

from label import *


class Main():

   def application_Launch(self):

       pass


   def render_main_view(self):

       l = Label("HelloWorld")

       l.color = "red"

       l.font_size = 21

       l.background_color = "white"

       l.left = 100

       l.top = 100

       l.width = 200

       l.height = 30

     

       l2 = Label("hhahha")

       l2.color = "red"

       l2.font_size = 21

       l2.background_color = "white"

       l2.left = 100

       l2.top = 300

       l2.width = 200

       l2.height = 30

       return json.dumps({

           "color": "purple",

           "subViews": [l.render(), l2.render()]

       })

label.py编写代码如下:


import json


class Label:

   def __init__(self, text):

       self.t = text

       self.color = ""

       self.left = 0

       self.top = 0

       self.width = 0

       self.height = 0

       self.font_size = 0

       self.background_color = ""

 

   def render(self):

       return json.dumps({

           "name": "Label",

           "t": self.t,

           "color": self.color,

           "left": self.left,

           "top": self.top,

           "width": self.width,

           "height": self.height,

           "font_size": self.font_size,

           "background_color": self.background_color

       })

到此,一个简易的Python iOS应用Demo工程就搭建完成了,上面代码创建了两个文本标签在页面上,并对组件的部分属性进行了配置,上面实现的每个类都非常简单,作为思路的演示,后续有时间会继续补充完善,并通过博客进行连载介绍,上面工程的运行效果如下图:

image.png



五、后续设想


通过DisplayLink来进行页面的变更刷新,为组件增加ID,设计一种算法来实现高效的页面刷新。

将组件的功能完善,添加更多原生组件的支持。

将事件进行包装,定义回调函数,让Python端有用处理事件的能力。

增加更多工具接口,如网络,数据文件操作等。

本篇博客内容比较缩略,你可以在如下地址找到完整的Demo工程:


https://github.com/ZYHshao/PyNativeDemo/tree/master/PyNativeDemo


需要注意,工程较大,原因是我将Python库也放了进去,这样可以保证你下载的代码是可运行的。

目录
相关文章
|
2天前
|
数据采集 NoSQL 中间件
python-scrapy框架(四)settings.py文件的用法详解实例
python-scrapy框架(四)settings.py文件的用法详解实例
8 0
|
2天前
|
存储 数据采集 数据库
python-scrapy框架(三)Pipeline文件的用法讲解
python-scrapy框架(三)Pipeline文件的用法讲解
6 0
|
2天前
|
存储 数据采集 JSON
python-scrapy框架(二)items文件夹的用法讲解
python-scrapy框架(二)items文件夹的用法讲解
10 0
|
2天前
|
数据采集 前端开发 中间件
python-scrapy框架(一)Spider文件夹的用法讲解
python-scrapy框架(一)Spider文件夹的用法讲解
9 0
|
10天前
|
存储 Swift iOS开发
使用Swift开发一个简单的iOS应用的详细步骤。
使用Swift开发iOS应用的步骤包括:创建Xcode项目,设计界面(Storyboard或代码),定义数据模型,实现业务逻辑,连接界面和逻辑,处理数据存储(如Core Data),添加网络请求(必要时),调试与测试,根据测试结果优化改进,最后提交至App Store或其它平台发布。
31 0
|
10天前
|
安全 Swift iOS开发
【Swift 开发专栏】Swift 与 UIKit:构建 iOS 应用界面
【4月更文挑战第30天】本文探讨了Swift和UIKit在构建iOS应用界面的关键技术和实践方法。Swift的简洁语法、类型安全和高效编程模型,加上与UIKit的紧密集成,使开发者能便捷地创建用户界面。UIKit提供视图、控制器、布局、动画和事件处理等功能,支持灵活的界面设计。实践中,遵循设计原则,合理组织视图层次,运用布局和动画,以及实现响应式设计,能提升界面质量和用户体验。文章通过登录、列表和详情界面的实际案例展示了Swift与UIKit的结合应用。
|
10天前
|
存储 安全 Swift
【Swift 开发专栏】使用 Swift 开发一个简单的 iOS 应用
【4月更文挑战第30天】本文介绍了使用 Swift 开发简单 iOS 待办事项应用的步骤。首先,阐述了 iOS 开发的吸引力及 Swift 语言的优势。接着,详细说明了应用的需求和设计,包括添加、查看和删除待办事项的功能。开发步骤包括创建项目、界面搭建、数据存储、功能实现,并提供了相关代码示例。最后,强调了实际开发中需注意的细节和优化,旨在帮助初学者掌握 Swift 和 iOS 开发基础。
|
11天前
|
缓存 前端开发 安全
Python web框架fastapi中间件的使用,CORS跨域详解
Python web框架fastapi中间件的使用,CORS跨域详解
|
11天前
|
API 数据库 Python
Python web框架fastapi数据库操作ORM(二)增删改查逻辑实现方法
Python web框架fastapi数据库操作ORM(二)增删改查逻辑实现方法
|
11天前
|
关系型数据库 MySQL API
Python web框架fastapi数据库操作ORM(一)
Python web框架fastapi数据库操作ORM(一)