Commit bd0060e6 by AppWaiBao

Initial commit

parents
File added
cat >> .gitignore <<'EOF'
# CocoaPods
Pods/
# Xcode
build/
DerivedData/
*.xcuserstate
.DS_Store
EOF
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
uuid = "A5A9D88B-D469-4D69-A0D2-BC676244A871"
type = "1"
version = "2.0">
</Bucket>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>KFWDispatch.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>4</integer>
</dict>
</dict>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:KFWDispatch.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
import SwiftUI
/// App 全局配置(对应安卓 AppConfig / configs.gradle)
enum AppConfig {
/// 包名(运行时自动读取,此处仅为兜底)
static let bundleID = Bundle.main.bundleIdentifier ?? "com.bendiyun.KFWMIS"
/// 版本名
static var versionName: String {
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.0"
}
/// 版本码
static var versionCode: String {
Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "1"
}
/// 服务器主机地址(对应安卓 configs.gradle 的 HOST_URL)
/// 注:当前后端只开放了 HTTPS,若需真机联调可临时改为 https://appmis4.kfw.net/
static let hostURL = "https://appmis4.kfw.net/"
/// 首页 H5 地址(对应安卓 HomeActivity 中硬编码的 url)
static let homeURL = "https://appmis4.kfw.net/index"
/// 是否调试模式
static var isDebug: Bool {
#if DEBUG
return true
#else
return false
#endif
}
}
extension Color {
/// 主题色(对应安卓 common_theme_color = #57BE85)
static let themeGreen = Color(hex: 0x57BE85)
/// 强调色(对应安卓 common_accent_color = #5A8DDF)
static let accentBlue = Color(hex: 0x5A8DDF)
// —— 以下 1:1 对应安卓 colors.xml / styles.xml ——
/// 窗口背景(common_window_background_color = #F4F4F4)
static let windowBackground = Color(hex: 0xF4F4F4)
/// 文本主色(common_text_color = #333333)
static let textPrimary = Color(hex: 0x333333)
/// 输入提示色(panda = #757575)
static let textHint = Color(hex: 0x757575)
/// 分割线(common_line_color = #ECECEC)
static let line = Color(hex: 0xECECEC)
/// 图标色(common_icon_color = #7C7C7C)
static let icon = Color(hex: 0x7C7C7C)
/// 按钮禁用(common_button_disable_color = #BBBBBB)
static let buttonDisabled = Color(hex: 0xBBBBBB)
/// 按钮按压(common_button_pressed_color = #AA5A8DDF)
static let buttonPressed = Color(hex: 0xAA5A8DDF)
/// 成功绿(SubmitButton succeedColor = #19CC95)
static let succeed = Color(hex: 0x19CC95)
/// 错误橙(SubmitButton errorColor = #FC8E34)
static let errorOrange = Color(hex: 0xFC8E34)
/// 左文字 black80 = #CC000000(约 80% 黑)
static let black80 = Color(red: 0, green: 0, blue: 0, opacity: 0.8)
/// 右文字 black60 = #99000000(约 60% 黑)
static let black60 = Color(red: 0, green: 0, blue: 0, opacity: 0.6)
/// black75 = #B000000F(约 69% 透明度,异常监控开关文字色)
static let black75 = Color(red: 0, green: 0, blue: 0, opacity: 0.69)
/// 按压背景 black5 = #0D000000
static let black5 = Color(red: 0, green: 0, blue: 0, opacity: 0.05)
/// 取消红(common_cancel_text_color = #F44336)
static let cancelRed = Color(hex: 0xF44336)
/// 确认蓝(common_confirm_text_color = #007AFF)
static let confirmBlue = Color(hex: 0x007AFF)
// —— 异常单按钮专属(对应安卓 yc_* / shape_btn_*)——
/// yc_one = #4F4F4F(数字/文字默认灰)
static let ycOne = Color(hex: 0x4F4F4F)
/// yc_two = #E99D24(橙,数量 1-10)
static let ycTwo = Color(hex: 0xE99D24)
/// yc_three = #BD3124(深红,数量 >10)
static let ycThree = Color(hex: 0xBD3124)
/// shape_btn_one = #00BE70(绿,数量 0)
static let abnormalGreen = Color(hex: 0x00BE70)
/// shape_abnormal 展开条背景 = #EFEFEF
static let expandBarBg = Color(hex: 0xEFEFEF)
}
extension Color {
/// 用十六进制初始化(支持 0xRRGGBB)
init(hex: UInt32, alpha: Double = 1.0) {
self.init(
.sRGB,
red: Double((hex >> 16) & 0xFF) / 255.0,
green: Double((hex >> 8) & 0xFF) / 255.0,
blue: Double(hex & 0xFF) / 255.0,
opacity: alpha
)
}
}
import UIKit
final class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
PushService.shared.start(launchOptions: launchOptions)
return true
}
}
import SwiftUI
@main
struct KFWDispatchApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
var body: some Scene {
WindowGroup {
RootView()
}
}
}
import SwiftUI
/// 根视图:根据登录态在「登录页 / 首页」之间切换(对应安卓 SplashActivity → Login/Home)
struct RootView: View {
@StateObject private var session = SessionManager.shared
var body: some View {
Group {
#if DEBUG
// 调试:可通过环境变量 KFW_DEBUG_SCREEN 直接显示指定页面,用于 UI 截图验证
switch ProcessInfo.processInfo.environment["KFW_DEBUG_SCREEN"] {
case "settings":
SettingsView()
case "abnormal":
AbnormalSettingView()
case "home":
HomeView()
default:
mainContent
}
#else
mainContent
#endif
}
}
@ViewBuilder
private var mainContent: some View {
if session.isLoggedIn {
HomeView()
} else {
LoginView()
}
}
}
import Foundation
import AVFoundation
import AudioToolbox
/// 异常订单监控(对应安卓 HomeActivity.requestData + abnormalCache)
/// 开关不申请系统权限:iOS 没有「震动权限」。声音走媒体音量播放 ring_bobao.mp3,震动调用系统振动。
final class AbnormalMonitor: ObservableObject {
/// 顺序与浮窗一致:5min未接、3min释放、15min迟送、催单
@Published var counts: [Int] = [0, 0, 0, 0]
private var timer: Timer?
private var acceptIDs: Set<String> = []
private var releaseIDs: Set<String> = []
private var deliveryIDs: Set<String> = []
private var reminderIDs: Set<String> = []
private var player: AVAudioPlayer?
func start() {
guard timer == nil else { return }
timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
self?.poll()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
self?.poll()
}
}
func stop() {
timer?.invalidate()
timer = nil
}
private func poll() {
Task { @MainActor in
do {
let res: (data: HttpData<AbnormalListResponse>, cookie: String?) = try await APIClient.request(
"amis/v1_0/order/abnormalOrder"
)
guard let data = res.data.data else { return }
let accept = ids(data.accept_list)
let release = ids(data.release_list)
let delivery = ids(data.delivery_list)
let reminder = ids(data.reminder_list)
let changed = hasNew(local: acceptIDs, incoming: accept)
|| hasNew(local: releaseIDs, incoming: release)
|| hasNew(local: deliveryIDs, incoming: delivery)
|| hasNew(local: reminderIDs, incoming: reminder)
acceptIDs = accept
releaseIDs = release
deliveryIDs = delivery
reminderIDs = reminder
counts = [accept.count, release.count, delivery.count, reminder.count]
if changed {
alert()
}
} catch {
// 轮询失败不打断页面,下一分钟再试
}
}
}
/// 对应安卓 compareBeanLists:新列表里出现本地没有的 id 才算有新异常
private func hasNew(local: Set<String>, incoming: Set<String>) -> Bool {
incoming.contains { !local.contains($0) }
}
private func ids(_ list: [AbnormalOrder]?) -> Set<String> {
Set((list ?? []).compactMap { $0.id }.filter { !$0.isEmpty })
}
private func alert() {
if AbnormalPreference.soundEnabled {
playSound()
}
if AbnormalPreference.vibrateEnabled {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
}
}
private func playSound() {
guard let url = Bundle.main.url(forResource: "ring_bobao", withExtension: "mp3") else { return }
do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(.playback, mode: .default, options: [])
try session.setActive(true)
player?.stop()
player = try AVAudioPlayer(contentsOf: url)
player?.prepareToPlay()
player?.play()
} catch {
player = nil
}
}
}
enum AbnormalPreference {
/// 缺省为开,对应安卓第一次初始化 sound = true
static var soundEnabled: Bool {
stored("sound")
}
static var vibrateEnabled: Bool {
stored("vibrate")
}
private static func stored(_ key: String) -> Bool {
if UserDefaults.standard.object(forKey: key) == nil { return true }
return UserDefaults.standard.bool(forKey: key)
}
}
struct AbnormalListResponse: Decodable {
let accept_list: [AbnormalOrder]?
let reminder_list: [AbnormalOrder]?
let release_list: [AbnormalOrder]?
let delivery_list: [AbnormalOrder]?
}
struct AbnormalOrder: Decodable {
let id: String?
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let text = try? container.decode(String.self, forKey: .id) {
id = text
} else if let number = try? container.decode(Int.self, forKey: .id) {
id = String(number)
} else {
id = nil
}
}
private enum CodingKeys: String, CodingKey {
case id
}
}
import Foundation
/// 登录接口返回(对应安卓 LoginApi.Response)
struct LoginResponse: Decodable {
let mobile: String
let role: Int
let roleDesc: String
let groupId: Int
let userId: Int
enum CodingKeys: String, CodingKey {
case mobile
case role
case roleDesc = "role_desc"
case groupId = "group_id"
case userId = "user_id"
}
}
enum AuthAPI {
/// 用户登录(POST amis/v1_0/quanta/login)
static func login(mobile: String, password: String) async throws -> (LoginResponse, cookie: String?) {
let body: [String: Any] = ["mobile": mobile, "passwd": password]
let res: (data: HttpData<LoginResponse>, cookie: String?) = try await APIClient.request(
"amis/v1_0/quanta/login",
body: body
)
guard let login = res.data.data else {
throw APIError.business(code: res.data.code, message: "登录返回数据为空")
}
return (login, res.cookie)
}
/// 退出登录(POST amis/v1_0/user/logout)
static func logout() async throws {
let _: (data: HttpData<NoData>, cookie: String?) = try await APIClient.request(
"amis/v1_0/user/logout"
)
}
}
import Foundation
/// 请求错误
enum APIError: LocalizedError {
case invalidURL
case business(code: String, message: String)
case tokenInvalid
case transport(Error)
var errorDescription: String? {
switch self {
case .invalidURL: return "请求地址无效"
case .business(_, let message): return message
case .tokenInvalid: return "登录已失效,请重新登录"
case .transport(let e): return e.localizedDescription
}
}
}
/// 统一接口数据结构(对应安卓 HttpData)
struct HttpData<T: Decodable>: Decodable {
let code: String
let msg: String?
let error: String?
let data: T?
enum CodingKeys: String, CodingKey {
case code = "respcd"
case msg = "respmsg"
case error = "resperr"
case data = "data"
}
var isSuccess: Bool { code == "0000" }
var isTokenFailure: Bool { code == "2002" || code == "2100" }
}
/// 空数据占位(用于无 data 的接口,如退出登录)
struct NoData: Decodable {}
/// 网络层(对应安卓 EasyHttp + RequestHandler + RequestServer)
enum APIClient {
/// 使用 ephemeral 配置:不自动处理/吞掉 Set-Cookie,
/// 这样我们才能像安卓一样手动读取 Set-Cookie 并自行管理登录态
private static let session: URLSession = {
let config = URLSessionConfiguration.ephemeral
config.httpShouldSetCookies = false
config.httpCookieAcceptPolicy = .never
return URLSession(configuration: config)
}()
static func request<T: Decodable>(
_ path: String,
method: String = "POST",
body: [String: Any]? = nil
) async throws -> (data: HttpData<T>, cookie: String?) {
guard let url = URL(string: AppConfig.hostURL + path) else {
throw APIError.invalidURL
}
var request = URLRequest(url: url)
request.httpMethod = method
request.timeoutInterval = 10
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// 全局请求头(对应安卓 AppApplication 中的拦截器)
request.setValue(CommonSDCache.shared.cookie, forHTTPHeaderField: "Cookie")
request.setValue("android_mis", forHTTPHeaderField: "device")
request.setValue(AppConfig.versionName, forHTTPHeaderField: "version_name")
request.setValue(AppConfig.versionCode, forHTTPHeaderField: "version")
if let body = body {
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
}
let (data, response) = try await Self.session.data(for: request)
let http = response as? HTTPURLResponse
// 非 2xx 状态码:给出友好错误(如 403 通常是被 WAF/风控拦截)
if let status = http?.statusCode, !(200..<300).contains(status) {
if status == 403 {
throw APIError.business(code: "\(status)", message: "请求被服务器拒绝(403),可能触发安全风控,请稍后重试")
}
throw APIError.business(code: "\(status)", message: "服务器错误(\(status))")
}
// 读取 Set-Cookie(可能是多个,这里取第一个,与安卓一致)
let setCookie = http?.value(forHTTPHeaderField: "Set-Cookie")
?? http?.allHeaderFields["Set-Cookie"] as? String
let result: HttpData<T>
do {
result = try JSONDecoder().decode(HttpData<T>.self, from: data)
} catch {
throw APIError.transport(error)
}
if result.isTokenFailure {
throw APIError.tokenInvalid
}
if !result.isSuccess {
throw APIError.business(code: result.code, message: result.msg ?? result.error ?? "请求失败")
}
return (result, setCookie)
}
}
import Foundation
/// 个推 iOS 应用参数(快服务调度端iOS)
/// 在个推控制台创建的应用:
/// 应用名称:快服务调度端iOS
/// bundleID:com.bendiyun.KFWMIS
enum GetuiConfig {
static let appId = "wNIKbIYrHV8bOJDaAaiI07"
static let appKey = "u1QjJm3cIg65wGXiJL1sE3"
static let appSecret = "KuF8gcqsHT9G25wLREItw6"
// Master Secret(EVTBtQ4s3bAM5uiDpsYOZ2)是服务端调用个推 REST API 用的,
// 客户端 SDK 不需要,不要填进客户端。
static var isConfigured: Bool {
!appId.isEmpty && !appKey.isEmpty && !appSecret.isEmpty
}
}
import UIKit
import UserNotifications
import AVFoundation
#if canImport(GTSDK)
import GTSDK
#endif
/// 对应安卓 GTPushService + PushMessageNotifier + KRingtoneManager。
/// 别名绑定保持和安卓一样:bindGtAlias() 整段是注释,不按 userId 绑定。
final class PushService: NSObject {
static let shared = PushService()
private var player: AVAudioPlayer?
func start(launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
guard GetuiConfig.isConfigured else {
NSLog("个推未配置 AppId / AppKey / AppSecret,跳过启动")
return
}
#if canImport(GTSDK)
GeTuiSdk.start(
withAppId: GetuiConfig.appId,
appKey: GetuiConfig.appKey,
appSecret: GetuiConfig.appSecret,
delegate: self,
launchingOptions: launchOptions
)
GeTuiSdk.registerRemoteNotification([.alert, .badge, .sound])
#else
NSLog("未链接 GTSDK。在工程目录执行 pod install 后用 KFWDispatch.xcworkspace 打开")
#endif
}
// 对应安卓 Helper.bindGtAlias(),目前安卓也是整段注释,不要按 userId 绑定。
// func bindAlias() {
// let userId = String(UserCache.shared.userId)
// guard !userId.isEmpty, userId != "0" else { return }
// GeTuiSdk.bindAlias(userId, andSequenceNum: "bind-\(userId)")
// }
fileprivate func handlePayload(_ userInfo: [AnyHashable: Any]) {
let data = payloadData(from: userInfo)
guard let data, let message = try? JSONDecoder().decode(KMessage.self, from: data) else {
NSLog("个推消息体解析失败")
return
}
postNotification(message)
if message.isLocal {
playRingtone(code: message.code)
}
}
private func payloadData(from userInfo: [AnyHashable: Any]) -> Data? {
if let text = userInfo["payload"] as? String {
return text.data(using: .utf8)
}
if let data = userInfo["payload"] as? Data {
return data
}
return try? JSONSerialization.data(withJSONObject: userInfo)
}
/// 对应安卓 PushMessageNotifier.send
private func postNotification(_ message: KMessage) {
let content = UNMutableNotificationContent()
let title = message.detail?.notifyTitle?.trimmingCharacters(in: .whitespacesAndNewlines)
content.title = (title?.isEmpty == false) ? title! : "快服务 - 新消息"
content.body = message.detail?.notifyContent ?? ""
content.sound = .default
if let shipId = message.detail?.shipId {
content.userInfo = ["ship_id": shipId, "order_id": message.detail?.orderId ?? ""]
}
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request)
}
/// 对应安卓 KRingtoneManager.playRingtone(KMessage):MS_003 用作废铃声,其余用分配铃声
private func playRingtone(code: String?) {
let name = code == "MS_003" ? "ring_zuo_fei" : "ring_fen_pei"
guard let url = Bundle.main.url(forResource: name, withExtension: "mp3") else { return }
do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(.playback, mode: .default)
try session.setActive(true)
player?.stop()
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch {
player = nil
}
}
}
#if canImport(GTSDK)
extension PushService: GeTuiSdkDelegate {
func geTuiSdkDidRegisterClient(_ clientId: String) {
NSLog("个推 cid = \(clientId)")
// 与安卓一致:bindGtAlias() 被注释,不按 userId 绑定别名。
// 如需按调度员账号关联,在这里把 clientId 上报后端。
}
func geTuiSdkDidOccurError(_ error: Error) {
NSLog("个推错误 \(error.localizedDescription)")
}
/// 透传消息。对应安卓 GeTuiIntentService.onReceiveMessageData → GTPushService
func geTuiSdkDidReceiveSlience(
_ userInfo: [AnyHashable: Any],
fromGetui: Bool,
offLine: Bool,
appId: String?,
taskId: String?,
msgId: String?,
fetchCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)? = nil
) {
handlePayload(userInfo)
completionHandler?(.newData)
}
/// APNs 通知在前台将要展示时回调(缺少此回调则前台收不到通知横幅)
func geTuiSdkNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
completionHandler([.badge, .sound, .banner])
}
/// 点击通知 / 冷启动回调(iOS 10+)
func geTuiSdkDidReceiveNotification(
_ userInfo: [AnyHashable: Any],
notificationCenter center: UNUserNotificationCenter?,
response: UNNotificationResponse?,
fetchCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)? = nil
) {
// 安卓点击通知跳 OrderDetailActivity。iOS 暂无订单详情页,先记录 ship_id 供后续跳转。
let shipId = userInfo["ship_id"] ?? userInfo["ship-id"]
NSLog("点击推送通知 userInfo=\(userInfo) ship_id=\(String(describing: shipId))")
completionHandler?(.noData)
}
}
#endif
/// 对应安卓 KMessage
struct KMessage: Decodable {
let msgId: Int?
let code: String?
let reportURL: String?
let time: Int64?
let detail: KMessageDetail?
let playType: String?
var isLocal: Bool { playType == "local" }
enum CodingKeys: String, CodingKey {
case msgId = "msg_id"
case code
case reportURL = "r_url"
case time
case detail
case playType = "play_type"
}
}
struct KMessageDetail: Decodable {
let orderId: String?
let shipId: Int?
let notifyTitle: String?
let notifyContent: String?
let orderType: Int?
let getType: Int?
let type: Int?
let ttsFlag: Int?
let tts: String?
let grabTime: Int?
enum CodingKeys: String, CodingKey {
case orderId = "order_id"
case shipId = "ship_id"
case notifyTitle = "notify_title"
case notifyContent = "notify_content"
case orderType = "order_type"
case getType = "get_type"
case type
case ttsFlag = "tts_flag"
case tts
case grabTime = "grab_time"
}
}
{
"colors" : [
{
"color" : {
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "0xDF",
"green" : "0x8D",
"red" : "0x5A"
}
},
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
{
"images" : [
{
"filename" : "AppIcon.png",
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
{
"images" : [
{
"filename" : "icon_right.png",
"idiom" : "universal",
"scale" : "1x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
{
"images" : [
{
"filename" : "login_logo.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>快服务调度端</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
<key>UILaunchScreen</key>
<dict/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>production</string>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
</dict>
</plist>
import Foundation
/// 通用存储(对应安卓 CommonSDCache,用 UserDefaults 代替 MMKV)
final class CommonSDCache {
static let shared = CommonSDCache()
private let defaults = UserDefaults.standard
private enum Key {
static let cookie = "Cookie"
static let lastLoginAccount = "common_last_login_account"
static let passwordBook = "common_pass_word_book"
}
/// 登录后的原始 Set-Cookie(例如 QFUSERSESSION=xxx; path=/)
/// H5 的 axios withCredentials 只认这个会话 Cookie,不认 userId
var cookie: String {
get { defaults.string(forKey: Key.cookie) ?? "" }
set { defaults.set(newValue, forKey: Key.cookie) }
}
/// 请求头里用的 name=value,去掉 path 等属性
var cookieHeader: String {
let raw = cookie.trimmingCharacters(in: .whitespacesAndNewlines)
guard !raw.isEmpty else { return "" }
let first = raw.split(separator: ";", maxSplits: 1).first.map(String.init) ?? raw
return first.trimmingCharacters(in: .whitespaces)
}
/// 给 WKWebView 用的 Cookie。安卓是 CookieManager.setCookie(url, setCookie)
func httpCookie(for url: URL) -> HTTPCookie? {
let header = cookieHeader
let parts = header.split(separator: "=", maxSplits: 1).map(String.init)
guard parts.count == 2, let host = url.host, !parts[1].isEmpty else { return nil }
return HTTPCookie(properties: [
.domain: host,
.path: "/",
.name: parts[0],
.value: parts[1],
.secure: true
])
}
var lastLoginAccount: String? {
get { defaults.string(forKey: Key.lastLoginAccount) }
set { defaults.set(newValue, forKey: Key.lastLoginAccount) }
}
/// 记住密码:手机号 -> 密码
var passwordBook: [String: String] {
get { defaults.dictionary(forKey: Key.passwordBook) as? [String: String] ?? [:] }
set { defaults.set(newValue, forKey: Key.passwordBook) }
}
}
/// 用户信息缓存(对应安卓 UserCache)
final class UserCache {
static let shared = UserCache()
private let defaults = UserDefaults.standard
private enum Key {
static let userId = "user_id"
static let userMobile = "user_mobile"
static let roleDesc = "role_desc"
}
var userId: Int {
get { defaults.integer(forKey: Key.userId) }
set { defaults.set(newValue, forKey: Key.userId) }
}
var userMobile: String {
get { defaults.string(forKey: Key.userMobile) ?? "" }
set { defaults.set(newValue, forKey: Key.userMobile) }
}
var roleDesc: String {
get { defaults.string(forKey: Key.roleDesc) ?? "" }
set { defaults.set(newValue, forKey: Key.roleDesc) }
}
}
enum PhoneFormat {
/// 安卓 SafeDialog:前 3 位 + **** + 后 4 位。号码用当前登录手机号,不再用写死的 18100001413
static func mask(_ mobile: String) -> String {
guard mobile.count >= 7 else { return mobile }
return "\(mobile.prefix(3))****\(mobile.suffix(4))"
}
}
/// 登录态管理(对应安卓 ActivityManager 跳转 + cookie 判断)
final class SessionManager: ObservableObject {
static let shared = SessionManager()
@Published var isLoggedIn: Bool = false
private init() {
isLoggedIn = !CommonSDCache.shared.cookie.isEmpty
}
func loginSucceed() {
isLoggedIn = true
}
func logout() {
CommonSDCache.shared.cookie = ""
isLoggedIn = false
}
}
import SwiftUI
/// 异常订单监控设置页(对应安卓 AbnormalSettingActivity,H5 gotoSetting 的目标页)
struct AbnormalSettingView: View {
@Environment(\.dismiss) private var dismiss
@AppStorage("sound") private var sound = true
@AppStorage("vibrate") private var vibrate = true
@State private var showLogoutConfirm = false
@State private var toastMessage: String?
private var roleText: String {
let value = UserCache.shared.roleDesc
return value.isEmpty ? "分站管理员" : value
}
private var mobileText: String {
UserCache.shared.userMobile
}
var body: some View {
NavigationView {
VStack(spacing: 0) {
SettingsTitleBar(title: "设置") { dismiss() }
ScrollView {
VStack(spacing: 0) {
SettingRow(title: "账号身份", value: roleText)
SettingDivider()
SettingRow(title: "当前账号", value: mobileText)
SettingDivider()
SettingRow(title: "消息中心", value: "查看", showArrow: true, action: {
toastMessage = "暂无消息"
})
Color.black5.frame(height: 10)
toggleRow("订单异常监控开关(声音)", isOn: $sound)
SettingDivider()
toggleRow("订单异常监控开关(震动)", isOn: $vibrate)
SettingDivider()
Spacer().frame(height: 30)
Button {
showLogoutConfirm = true
} label: {
Text("退出登录")
}
.buttonStyle(CapsuleButtonStyle())
.padding(.horizontal, 50)
.padding(.bottom, 30)
}
}
}
.background(Color.windowBackground)
.navigationBarHidden(true)
.toast($toastMessage)
.onChange(of: sound) { value in
toastMessage = value ? "声音已开启" : "声音已关闭"
}
.onChange(of: vibrate) { value in
toastMessage = value ? "震动已开启" : "震动已关闭"
}
.confirmationDialog("确认退出登录?", isPresented: $showLogoutConfirm, titleVisibility: .visible) {
Button("退出登录", role: .destructive) { logout() }
Button("取消", role: .cancel) {}
}
}
.navigationViewStyle(.stack)
}
private func toggleRow(_ title: String, isOn: Binding<Bool>) -> some View {
HStack(spacing: 0) {
Text(title)
.font(.system(size: 16))
.foregroundColor(Color.black75)
.frame(maxWidth: .infinity, alignment: .leading)
Toggle("", isOn: isOn)
.labelsHidden()
.tint(Color.themeGreen)
.scaleEffect(0.9)
}
.padding(.horizontal, 15)
.padding(.vertical, 15)
.background(Color.white)
}
/// 对应安卓 AbnormalSettingActivity.loginOut:请求退出接口,清 Cookie,回到登录页
private func logout() {
Task { @MainActor in
try? await AuthAPI.logout()
SessionManager.shared.logout()
dismiss()
}
}
}
import SwiftUI
/// 设置列表行(1:1 对应安卓 SettingBar)
/// 左文字 black80 / 15pt,右文字 black60 / 14pt,padding 左右15 上下12,分割线 #ECECEC
struct SettingRow: View {
let title: String
var value: String = ""
var badge: Bool = false
var showArrow: Bool = false
var destructive: Bool = false
var action: (() -> Void)? = nil
var body: some View {
Button {
action?()
} label: {
HStack(spacing: 0) {
Text(title)
.font(.system(size: 15))
.foregroundColor(destructive ? Color.cancelRed : Color.black80)
.frame(maxWidth: .infinity, alignment: .leading)
if badge {
Text("new")
.font(.system(size: 11))
.foregroundColor(.white)
.padding(.horizontal, 6)
.padding(.vertical, 2)
.background(Color.cancelRed)
.clipShape(Capsule())
.padding(.trailing, 10)
}
if !value.isEmpty {
Text(value)
.font(.system(size: 14))
.foregroundColor(Color.black60)
.lineLimit(1)
}
if showArrow {
Image(systemName: "chevron.right")
.font(.system(size: 13, weight: .semibold))
.foregroundColor(Color.icon)
.padding(.leading, 8)
}
}
.padding(.horizontal, 15)
.padding(.vertical, 12)
.contentShape(Rectangle())
}
.buttonStyle(SettingRowButtonStyle())
}
}
/// SettingBar 按压态:按压时背景 black5(对应安卓 StateListDrawable)
struct SettingRowButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.background(configuration.isPressed ? Color.black5 : Color.white)
}
}
/// 分割线(对应安卓 1px #ECECEC)
struct SettingDivider: View {
var body: some View {
Rectangle()
.fill(Color.line)
.frame(height: 1 / UIScreen.main.scale)
}
}
/// 记住密码复选框(对应安卓 radiobutton_selector,选中蓝色 #5A8DDF)
struct CheckboxToggleStyle: ToggleStyle {
func makeBody(configuration: Configuration) -> some View {
Button {
configuration.isOn.toggle()
} label: {
HStack(spacing: 8) {
Image(systemName: configuration.isOn ? "checkmark.square.fill" : "square")
.font(.system(size: 18))
.foregroundColor(configuration.isOn ? Color.accentBlue : Color.icon)
configuration.label
}
}
.buttonStyle(.plain)
}
}
/// 主按钮样式(对应安卓 ButtonStyle:胶囊形圆角 999dp,强调色 #5A8DDF,文字 white90)
struct CapsuleButtonStyle: ButtonStyle {
var enabled: Bool = true
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(.system(size: 15))
.foregroundColor(.white.opacity(0.9))
.frame(maxWidth: .infinity)
.frame(height: 44)
.background(
Capsule()
.fill(configuration.isPressed ? Color.buttonPressed
: enabled ? Color.accentBlue : Color.buttonDisabled)
)
.animation(.easeOut(duration: 0.15), value: configuration.isPressed)
}
}
/// 分组的标题条(组间留白,对应安卓 marginTop 15dp)
struct SectionGap: View {
var body: some View {
Color.windowBackground.frame(height: 15)
}
}
/// 短暂提示(对应安卓 ToastUtils.show)
struct ToastModifier: ViewModifier {
@Binding var message: String?
func body(content: Content) -> some View {
content.overlay {
if let message {
Text(message)
.font(.system(size: 14))
.foregroundColor(.white)
.multilineTextAlignment(.center)
.padding(.horizontal, 16)
.padding(.vertical, 10)
.background(Color.black.opacity(0.75))
.cornerRadius(8)
.padding(.horizontal, 40)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.6) {
if self.message == message {
self.message = nil
}
}
}
}
}
}
}
extension View {
func toast(_ message: Binding<String?>) -> some View {
modifier(ToastModifier(message: message))
}
}
import SwiftUI
/// 异常单悬浮按钮(1:1 对应安卓 CashTaskView + view_cash_task.xml)
///
/// 交互:
/// - 可上下拖动(松手回弹到最右,对应安卓 translationX 回弹)
/// - 点击按钮:向左展开成 4 列横条(宽度 44→98% 屏宽,300ms)
/// - 点击展开条内任意列 / 再点按钮:向右收起,点列还会调用 H5 的 navigateToPage('N')
struct AbnormalFloatView: View {
let webModel: WebViewModel
@ObservedObject var monitor: AbnormalMonitor
@State private var expanded = false
@State private var offsetY: CGFloat = 0
@State private var dragBaseY: CGFloat = 0
/// 顺序与浮窗一致:5min未接、3min释放、15min迟送、催单
private var counts: [Int] { monitor.counts }
private let titles = ["5min未接", "3min释放", "15min迟送", "催单"]
private let btnW: CGFloat = 86 // 对应安卓 yc_btn 86dp
private let btnH: CGFloat = 44 // 对应安卓 44dp
init(webModel: WebViewModel, monitor: AbnormalMonitor) {
self.webModel = webModel
self.monitor = monitor
#if DEBUG
// 调试:KFW_FLOAT_EXPANDED=1 时初始展开,用于截图验证
if ProcessInfo.processInfo.environment["KFW_FLOAT_EXPANDED"] == "1" {
_expanded = State(initialValue: true)
}
#endif
}
var body: some View {
GeometryReader { geo in
let totalW = geo.size.width * 0.98 // 对应安卓 screenWidth = 屏宽 * 0.98
let barW = totalW - btnW
HStack(spacing: 0) {
HStack(spacing: 0) {
ForEach(0..<4, id: \.self) { i in
itemColumn(i, width: barW / 4)
}
}
.frame(width: expanded ? barW : 0, height: btnH)
.background(Color.expandBarBg)
.clipped()
Button {
toggle()
} label: {
HStack(spacing: 2) {
Image("icon_right")
.resizable()
.scaledToFit()
.frame(width: 22, height: 22)
Text("异常单")
.font(.system(size: 14, weight: .bold))
.foregroundColor(.white)
}
.frame(width: btnW, height: btnH)
.background(buttonColor)
}
.buttonStyle(.plain)
}
.frame(width: (expanded ? barW : 0) + btnW, height: btnH, alignment: .trailing)
.clipShape(LeftCapsuleShape())
.shadow(color: .black.opacity(0.18), radius: 4, y: 2)
.simultaneousGesture(
DragGesture(minimumDistance: 8)
.onChanged { value in
offsetY = dragBaseY + value.translation.height
}
.onEnded { value in
dragBaseY = offsetY
let minY = -(geo.size.height - btnH - 60 - 222)
offsetY = min(max(offsetY, minY), 0)
dragBaseY = offsetY
}
)
.position(
x: geo.size.width - ((expanded ? barW : 0) + btnW) / 2,
y: geo.size.height - btnH / 2 - 222 + offsetY
)
}
}
private func itemColumn(_ index: Int, width: CGFloat) -> some View {
Button {
// 对应安卓:webView.loadUrl("javascript:navigateToPage('N')") + toast + contract()
webModel.callJS("navigateToPage('\(index + 1)')")
withAnimation(.easeOut(duration: 0.3)) { expanded = false }
} label: {
VStack(spacing: 2) {
Text("\(counts[index])")
.font(.system(size: 16, weight: .bold))
.foregroundColor(countColor(counts[index]))
Text(titles[index])
.font(.system(size: 10))
.foregroundColor(Color.ycOne)
}
.frame(width: width, height: btnH)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
private func toggle() {
withAnimation(.easeOut(duration: 0.3)) { expanded.toggle() }
}
/// 数字颜色(对应安卓 setTextColor):0 灰 / 1-10 橙 / >10 红
private func countColor(_ count: Int) -> Color {
if count == 0 { return .ycOne }
else if count <= 10 { return .ycTwo }
else { return .ycThree }
}
/// 按钮背景色(对应安卓 setBackground):0 绿 / 1-10 橙 / >10 红(取最大值)
private var buttonColor: Color {
let maxCount = counts.max() ?? 0
if maxCount == 0 { return .abnormalGreen }
else if maxCount <= 10 { return .ycTwo }
else { return .ycThree }
}
}
/// 左边半圆、右边直角的形状(对应安卓 shape_btn / shape_abnormal 的 left 圆角 right 直角)
struct LeftCapsuleShape: Shape {
func path(in rect: CGRect) -> Path {
let r = rect.height / 2
var p = Path()
p.move(to: CGPoint(x: rect.minX + r, y: rect.minY))
p.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) // 上边 → 右
p.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) // 右边 → 下
p.addLine(to: CGPoint(x: rect.minX + r, y: rect.maxY)) // 下边 → 左
p.addArc(center: CGPoint(x: rect.minX + r, y: rect.midY),
radius: r,
startAngle: .degrees(90),
endAngle: .degrees(270),
clockwise: false) // 左边半圆
p.closeSubpath()
return p
}
}
import SwiftUI
/// 首页:H5 容器 + 异常单浮窗(对应安卓 HomeActivity + CashTaskView)
/// 右上角齿轮是首页 H5 自己画的,只在 /index 出现,点击 window.android.gotoSetting()
/// 打开的是异常监控设置页,不是 SettingActivity 那套模板页。
struct HomeView: View {
@StateObject private var webModel = WebViewModel()
@StateObject private var monitor = AbnormalMonitor()
@State private var showAbnormalSetting = false
var body: some View {
ZStack(alignment: .bottomTrailing) {
WebViewContainer(
model: webModel,
urlString: AppConfig.homeURL,
onGotoSetting: { showAbnormalSetting = true }
)
.ignoresSafeArea(edges: .top)
AbnormalFloatView(webModel: webModel, monitor: monitor)
}
.fullScreenCover(isPresented: $showAbnormalSetting) {
AbnormalSettingView()
}
.onAppear { monitor.start() }
.onDisappear { monitor.stop() }
}
}
import SwiftUI
/// 登录页(1:1 对应安卓 LoginActivity + login_activity.xml)
struct LoginView: View {
@StateObject private var viewModel = LoginViewModel()
@FocusState private var focusedField: Field?
private enum Field { case phone, password }
var body: some View {
NavigationView {
VStack(spacing: 0) {
// 顶部透明标题栏占位(对应安卓透明 TitleBar,高 50dp)
Color.clear.frame(height: 50)
ScrollView {
VStack(spacing: 0) {
// Logo(对应安卓 bg_login 120dp,margin vertical 10dp)
Image("login_logo")
.resizable()
.scaledToFit()
.frame(width: 120, height: 120)
.padding(.vertical, 10)
// 表单区(对应安卓 ll_login_body)
VStack(spacing: 0) {
// 手机号输入框(margin 40,hint 请输入手机号码)
TextField("请输入手机号码", text: $viewModel.phone)
.font(.system(size: 15))
.keyboardType(.numberPad)
.textContentType(.telephoneNumber)
.padding(.horizontal, 40)
.padding(.vertical, 10)
.focused($focusedField, equals: .phone)
// 分割线(margin 40)
Color.line.frame(height: 1).padding(.horizontal, 40)
// 密码输入框(marginTop 15)
SecureField("请输入密码", text: $viewModel.password)
.font(.system(size: 15))
.padding(.horizontal, 40)
.padding(.top, 15)
.padding(.bottom, 10)
.focused($focusedField, equals: .password)
// 分割线
Color.line.frame(height: 1).padding(.horizontal, 40)
}
// 记住密码(对应安卓 CheckBox,选中蓝色)
Toggle(isOn: $viewModel.rememberPassword) {
Text("记住密码")
.font(.system(size: 14))
.foregroundColor(Color.accentBlue)
}
.toggleStyle(CheckboxToggleStyle())
.padding(.horizontal, 40)
.padding(.top, 15)
// 登录按钮(对应安卓 SubmitButton,marginTop 30)
Button(action: { viewModel.login() }) {
ZStack {
if viewModel.isLoading {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .white))
} else {
Text("登录")
}
}
}
.buttonStyle(CapsuleButtonStyle(enabled: viewModel.canSubmit))
.disabled(!viewModel.canSubmit)
.padding(.horizontal, 40)
.padding(.top, 30)
Spacer(minLength: 0)
}
.padding(.top, 20)
}
}
.background(Color.white)
.navigationBarHidden(true)
.alert("提示", isPresented: $viewModel.showError) {
Button("确定", role: .cancel) {}
} message: {
Text(viewModel.errorMessage ?? "")
}
}
.navigationViewStyle(.stack)
.onAppear {
#if DEBUG
// 调试自动登录:xcrun simctl launch 时加 SIMCTL_CHILD_KFW_AUTOLOGIN=1 触发
if ProcessInfo.processInfo.environment["KFW_AUTOLOGIN"] == "1",
viewModel.phone.isEmpty {
viewModel.phone = "18186037141"
viewModel.password = "123qwe"
viewModel.login()
}
#endif
}
}
}
import Foundation
/// 登录页 ViewModel(对应安卓 LoginActivity)
final class LoginViewModel: ObservableObject {
@Published var phone: String = ""
@Published var password: String = ""
@Published var rememberPassword: Bool = true
@Published var isLoading: Bool = false
@Published var errorMessage: String?
@Published var showError: Bool = false
init() {
// 预填最近登录账号与记住的密码(对应安卓 LoginActivity.initData)
if let account = CommonSDCache.shared.lastLoginAccount {
phone = account
password = CommonSDCache.shared.passwordBook[account] ?? ""
}
}
var canSubmit: Bool {
phone.count == 11 && !password.isEmpty && !isLoading
}
func login() {
guard canSubmit else { return }
isLoading = true
errorMessage = nil
Task { @MainActor in
defer { isLoading = false }
do {
let (login, cookie) = try await AuthAPI.login(mobile: phone, password: password)
// 保存 cookie 与用户信息(对应安卓 LoginActivity.onSucceed)
// H5 登录态只看 Set-Cookie 里的 QFUSERSESSION,没有它首页就是未登录
guard let cookie = cookie, !cookie.isEmpty else {
errorMessage = "登录成功但没有拿到会话 Cookie"
showError = true
return
}
CommonSDCache.shared.cookie = cookie
UserCache.shared.userId = login.userId
UserCache.shared.userMobile = login.mobile
UserCache.shared.roleDesc = login.roleDesc
// 最近登录账号 + 记住密码
CommonSDCache.shared.lastLoginAccount = phone
var book = CommonSDCache.shared.passwordBook
if rememberPassword {
book[phone] = password
} else {
book.removeValue(forKey: phone)
}
CommonSDCache.shared.passwordBook = book
SessionManager.shared.loginSucceed()
} catch {
errorMessage = error.localizedDescription
showError = true
}
}
}
}
import SwiftUI
import WebKit
/// WKWebView 封装(对应安卓 BaseWebView + JavascriptAction)
struct WebViewContainer: UIViewRepresentable {
@ObservedObject var model: WebViewModel
let urlString: String
let onGotoSetting: () -> Void
func makeCoordinator() -> Coordinator {
Coordinator(onGotoSetting: onGotoSetting)
}
func makeUIView(context: Context) -> WKWebView {
let configuration = WKWebViewConfiguration()
let controller = WKUserContentController()
// 注入 window.android 桥(对应安卓 addJavascriptInterface(mJavascriptAction, "android"))
// 让已有 H5 代码 window.android.gotoSetting() / window.android.getVersion() 无需改动即可运行
let version = AppConfig.versionName
let js = """
window.android = {
gotoSetting: function() { window.webkit.messageHandlers.android.postMessage('gotoSetting'); },
getVersion: function() { return 'v\(version)'; }
};
"""
let script = WKUserScript(source: js, injectionTime: .atDocumentStart, forMainFrameOnly: false)
controller.addUserScript(script)
controller.add(context.coordinator, name: "android")
configuration.userContentController = controller
let webView = WKWebView(frame: .zero, configuration: configuration)
webView.navigationDelegate = context.coordinator
webView.allowsBackForwardNavigationGestures = true
// 隐藏 H5 底栏「我的」:footerApp.vue 里
// n.value = /Android/i.test(navigator.userAgent)
// n.value 为 true 时不渲染「我的」Tab。
// 安卓 WebView 的 UA 自带 Android,所以那个 Tab 不出现。
// iOS 默认 UA 是 iPhone,这里改成带 Android 的 UA,走同一段判断。
webView.customUserAgent = """
Mozilla/5.0 (Linux; Android 14; Pixel 7 Build/UP1A.231005.007) \
AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 \
Chrome/120.0.6099.230 Mobile Safari/537.36
"""
// 自动处理 safe area:顶部刘海由 .automatic 加 inset 避开,底部 Home Indicator 也自动避开
webView.scrollView.contentInsetAdjustmentBehavior = .automatic
model.webView = webView
loadPage(in: webView)
return webView
}
/// 对应安卓 HomeActivity.initWebView:先清掉旧 Cookie,再把登录的 QFUSERSESSION 写进 WebView,然后加载首页。
/// WKWebView 不读 HTTPCookieStorage.shared,必须写到 WKHTTPCookieStore,并且等 setCookie 完成后再 load。
private func loadPage(in webView: WKWebView) {
guard let url = URL(string: urlString) else { return }
let store = webView.configuration.websiteDataStore.httpCookieStore
store.getAllCookies { cookies in
let stale = cookies.filter { $0.domain.contains("kfw.net") }
Self.deleteCookies(stale, in: store) {
let finish = {
DispatchQueue.main.async {
var request = URLRequest(url: url)
let header = CommonSDCache.shared.cookieHeader
if !header.isEmpty {
request.setValue(header, forHTTPHeaderField: "Cookie")
}
webView.load(request)
}
}
if let cookie = CommonSDCache.shared.httpCookie(for: url) {
store.setCookie(cookie) { finish() }
} else {
finish()
}
}
}
}
private static func deleteCookies(
_ cookies: [HTTPCookie],
in store: WKHTTPCookieStore,
completion: @escaping () -> Void
) {
guard let first = cookies.first else {
completion()
return
}
store.delete(first) {
deleteCookies(Array(cookies.dropFirst()), in: store, completion: completion)
}
}
func updateUIView(_ uiView: WKWebView, context: Context) {}
final class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
let onGotoSetting: () -> Void
init(onGotoSetting: @escaping () -> Void) {
self.onGotoSetting = onGotoSetting
}
func userContentController(
_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage
) {
guard message.name == "android" else { return }
if let method = message.body as? String, method == "gotoSetting" {
onGotoSetting()
}
}
}
}
import Foundation
import WebKit
/// H5 桥接与页面控制(对应安卓 BaseWebView + JavascriptAction + CashTaskView)
final class WebViewModel: ObservableObject {
weak var webView: WKWebView?
/// 原生调用 H5(对应安卓 webView.loadUrl("javascript:..."))
func callJS(_ script: String) {
webView?.evaluateJavaScript(script, completionHandler: nil)
}
}
platform :ios, '15.6'
use_frameworks!
inhibit_all_warnings!
target 'KFWDispatch' do
pod 'GTSDK', '3.1.2.0'
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.6'
end
end
end
PODS:
- GTCommonSDK (3.2.7.0):
- ZXSDK
- GTSDK (3.1.2.0):
- GTCommonSDK (> 3.0.9.0)
- ZXSDK (3.3.3)
DEPENDENCIES:
- GTSDK (= 3.1.2.0)
SPEC REPOS:
trunk:
- GTCommonSDK
- GTSDK
- ZXSDK
SPEC CHECKSUMS:
GTCommonSDK: d4ca7956556a2803f8c3edc167812c52009165e2
GTSDK: 766d59a91808ac58ea12c7285f22a3fa27793abc
ZXSDK: ae61fd6163428d62bf5b12e4c90ac9840d58ca54
PODFILE CHECKSUM: 89f5cf7eb1b411ae9e194bcf8fdd3639325d4d7b
COCOAPODS: 1.16.2
name: KFWDispatch
options:
bundleIdPrefix: com.kfw
deploymentTarget:
iOS: "15.6"
createIntermediateGroups: true
settings:
base:
SWIFT_VERSION: "5.0"
IPHONEOS_DEPLOYMENT_TARGET: "15.6"
targets:
KFWDispatch:
type: application
platform: iOS
deploymentTarget: "15.6"
sources:
- path: KFWDispatch
excludes:
- Resources/Info.plist
settings:
base:
# 个推 iOS 应用登记的 bundle id
PRODUCT_BUNDLE_IDENTIFIER: com.bendiyun.KFWMIS
MARKETING_VERSION: "1.0.0"
CURRENT_PROJECT_VERSION: "1"
TARGETED_DEVICE_FAMILY: "1"
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME: AccentColor
SUPPORTS_MACCATALYST: NO
CODE_SIGN_STYLE: Automatic
DEVELOPMENT_TEAM: S3SN9ALHA9
CODE_SIGN_ENTITLEMENTS: KFWDispatch/Resources/KFWDispatch.entitlements
configs:
release:
# 正式包使用 aps-environment=production 的 entitlements
CODE_SIGN_ENTITLEMENTS: KFWDispatch/Resources/KFWDispatch-Release.entitlements
info:
path: KFWDispatch/Resources/Info.plist
properties:
CFBundleDisplayName: 快服务调度端
CFBundleShortVersionString: "1.0.0"
CFBundleVersion: "1"
UILaunchScreen: {}
UISupportedInterfaceOrientations:
- UIInterfaceOrientationPortrait
UIBackgroundModes:
- remote-notification
NSAppTransportSecurity:
NSAllowsArbitraryLoads: true
ITSAppUsesNonExemptEncryption: false
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment