Im getting errors the first time the swiftui application opens.
the user first see the option to accept notifications (then it goes away really fast)
then i see the option to allow the app to find and connect to devices in the network
lastly, i see the option to accept notifications again.
here is a video of the issue::
https://youtu.be/d4t277ft9Os
once i accept all the options, i close the app and reopen it and everything works fine
This is the error that I am seeing in the terminal ::
2024-01-12 18:14:21.503069-0500 dayt[1239:215953] Connection 1: received failure notification
2024-01-12 18:14:21.503131-0500 dayt[1239:215953] Connection 1: failed to connect 1:50, reason -1
2024-01-12 18:14:21.503158-0500 dayt[1239:215953] Connection 1: encountered error(1:50)
2024-01-12 18:14:21.503892-0500 dayt[1239:215953] Task <2401ED73-1EBF-41ED-959E-2B086AB4C7B1>.<1> HTTP load failed, 0/0 bytes (error code: -1009 [1:50])
2024-01-12 18:14:21.510801-0500 dayt[1239:215955] Task <2401ED73-1EBF-41ED-959E-2B086AB4C7B1>.<1> finished with error [-1009] Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={_kCFStreamErrorCodeKey=50, NSUnderlyingError=0x2818d9230 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_NSURLErrorNWPathKey=unsatisfied (Local network prohibited), interface: en0[802.11], ipv4, _kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <2401ED73-1EBF-41ED-959E-2B086AB4C7B1>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <2401ED73-1EBF-41ED-959E-2B086AB4C7B1>.<1>"
), NSLocalizedDescription=The Internet connection appears to be offline., NSErrorFailingURLStringKey=http://192.168.0.8:3000/socket.io/?transport=polling&b64=1&EIO=4, NSErrorFailingURLKey=http://192.168.0.8:3000/socket.io/?transport=polling&b64=1&EIO=4, _kCFStreamErrorDomainKey=1}
2024-01-12 18:14:21.683981-0500 dayt[1239:215953] Connection 2: received failure notification
2024-01-12 18:14:21.684014-0500 dayt[1239:215953] Connection 2: failed to connect 1:50, reason -1
2024-01-12 18:14:21.684027-0500 dayt[1239:215953] Connection 2: encountered error(1:50)
2024-01-12 18:14:21.684771-0500 dayt[1239:215954] Task <1F0C0E34-9E54-427A-A3C8-73F0572BA727>.<1> HTTP load failed, 0/0 bytes (error code: -1009 [1:50])
2024-01-12 18:14:21.685004-0500 dayt[1239:215955] Task <1F0C0E34-9E54-427A-A3C8-73F0572BA727>.<1> finished with error [-1009] Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={_kCFStreamErrorCodeKey=50, NSUnderlyingError=0x28182de60 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_NSURLErrorNWPathKey=unsatisfied (Local network prohibited), interface: en0[802.11], ipv4, _kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <1F0C0E34-9E54-427A-A3C8-73F0572BA727>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <1F0C0E34-9E54-427A-A3C8-73F0572BA727>.<1>"
), NSLocalizedDescription=The Internet connection appears to be offline., NSErrorFailingURLStringKey=http://192.168.0.8:3000/socket.io/?transport=polling&b64=1&EIO=4, NSErrorFailingURLKey=http://192.168.0.8:3000/socket.io/?transport=polling&b64=1&EIO=4, _kCFStreamErrorDomainKey=1}
this is the code that is applicable::
// ContentView.swift
import SwiftUI
struct ContentView: View {
@EnvironmentObject private var appDelegate: AppDelegate
@EnvironmentObject var sheet_manager: SheetManager
@ObservedObject private var chatViewModel = ChatViewModel()
@AppStorage("screen_width") private var screen_width: String?
@AppStorage("screen_height") private var screen_height: String?
var body: some View {
GeometryReader { geometry in
NavigationStack {
// AuthView()
// .onAppear {
// screen_height = "\(geometry.size.height)"
// screen_width = "\(geometry.size.width)"
//
// }
}
.environmentObject(chatViewModel) // Inject the ChatViewModel into the environment
}
}
}
code2::
// daytApp.swift
import SwiftUI
@main
struct daytApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(appDelegate) // Provide the AppDelegate as an environment object
}
}
}
code3::
// AppDelegate.swift
import UIKit
import UserNotifications
class AppDelegate: NSObject, UIApplicationDelegate, ObservableObject {
@Published var deviceToken: String? // Observable property to update SwiftUI view
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Request notification permission when the app launches
self.requestNotificationPermission()
return true
}
func requestNotificationPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
print("Notification permission granted")
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
} else if let error = error {
print("Error requesting notification permission: \(error.localizedDescription)")
}
}
}
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenComponents = deviceToken.map { data in String(format: "%02.2hhx", data) }
let deviceTokenString = tokenComponents.joined()
// Update the device token in the ObservableObject
print("deviceTokenString: ",deviceTokenString)
self.deviceToken = deviceTokenString
}
}
i think the issue is that the its loading to fast or something along those lines.
i found this stackoverflow but it dont help::
iOS: Adding SwiftUI to project – not loading scene correctly
===========
Now that i look at the issue a bit closed, it think it might have something to do with my websocket connection::
import SocketIO
import SwiftUI
class ChatViewModel: ObservableObject {
@Published var messages: [ChatMessage] = []
var chatService: ChatService
init() {
self.chatService = ChatService()
chatService.$messages
.assign(to: &$messages)
}
}
final class ChatService: ObservableObject {
private var base_url = "chat_message-"
private var token_app_storage_util = TokenAppStorageUtil()
private var is_chat_edit_view_visible_storage_util = IsChatEditViewVisibleAppStorageUtil()
@AppStorage("access_token") var accessToken: String?
@Published var messages = [ChatMessage]()
init() {
setupSocket()
}
func connect() {
setupSocket()
}
func disconnect() {
manager.defaultSocket.emit("disconnect", ["token": self.token_app_storage_util.get_access_token()])
manager.defaultSocket.disconnect()
}
private func setupSocket() {
let socket = manager.defaultSocket
socket.on(clientEvent: .connect) { [weak self] (data, ack) in
// Send JWT token after connection is established
if let token = self?.accessToken {
let data = ["token": token]
socket.emit("authenticate", token)
}
}
socket.on("\(self.base_url)message_created") { [self] (data, ack) in
if let dictionaries = data[0] as? [[String: Any]] {
let messages = dictionaries.map { dictionary in
let msg = ChatMessage(
id: dictionary["id"] as? String ?? "",
active: (dictionary["active"] as? Bool)!,
created_by: dictionary["created_by"] as? String ?? "",
updated_by: dictionary["updated_by"] as? String ?? "",
created_on: dictionary["created_on"] as? String ?? "",
updated_on: dictionary["updated_on"] as? String ?? "",
message: dictionary["message"] as? String ?? "",
chat_id: dictionary["chat_id"] as? String ?? ""
)
if is_chat_edit_view_visible_storage_util.get_is_chat_edit_view_visible() {
print("Message receieved INSIDE ",msg.message)
}else{
print("Message receieved OUTSIDE ",msg.message)
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "New msg"
content.body = msg.message
let request = UNNotificationRequest(
identifier:msg.id,
content: content,
trigger: nil
)
center.add(request){ error in
if let error = error {
print(error)
}
}
}
return msg
}
DispatchQueue.main.async {
self.messages.append(contentsOf: messages)
}
}
}
socket.connect()
}
func reconnect() {
manager.defaultSocket.disconnect()
setupSocket()
}
func getAccessToken() -> String? {
return accessToken
}
private lazy var server_url: String = {
guard let url = PlistReaderUtil.getInfoPlistValue(forKey: "server_url") else {
fatalError("Server URL not found in Config.plist")
}
return url
}()
internal lazy var manager: SocketManager = {
SocketManager(socketURL: URL(string: server_url)!, config: [.log(false), .compress])
}()
func create_chat_message(message: String, chat_id: String) {
print("[ChatService] create_chat_message() \n\n")
let socket = manager.defaultSocket
var query_params: [String: String] = [
"chat_id": "\(chat_id)",
"message": "\(message)"
]
socket.emit("\(self.base_url)create", query_params)
}
func get_chat_messages(chat_id: String, completion: @escaping ([ChatMessage]) -> Void) {
print("[ChatService] get_chat_messages() \n", chat_id)
let socket = manager.defaultSocket
var query_params: [String: String] = [
"chat_id": "=$\(chat_id)",
]
socket.on("\(self.base_url)get") { data, ack in
// print("DATA ON get",data)
if let dictionaries = data[0] as? [[String: Any]] {
let messages = dictionaries.map { dictionary in
var msg = ChatMessage(
id: dictionary["id"] as? String ?? "",
active: (dictionary["active"] as? Bool)!,
created_by: dictionary["created_by"] as? String ?? "",
updated_by: dictionary["updated_by"] as? String ?? "",
created_on: dictionary["created_on"] as? String ?? "",
updated_on: dictionary["updated_on"] as? String ?? "",
message: dictionary["message"] as? String ?? "",
chat_id: dictionary["chat_id"] as? String ?? ""
)
print("MSG:",msg)
return msg
}
DispatchQueue.main.async {
self.messages.append(contentsOf: messages)
}
}
}
socket.emit("\(self.base_url)get", query_params)
}
}




