Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disconnect and reconnect stream on background #204

Closed
wants to merge 3 commits into from

Conversation

humanagent
Copy link
Contributor

@humanagent humanagent commented Dec 6, 2023

After running some tests, the stream fails silently after 4-10 minutes of the app being in the background.

I've implemented a solution addressing streams intermittently stopping after the app is backgrounded and re-foregrounded. The solution involves listening for specific app state notifications and managing the stream accordingly.

Here's the relevant code:

// Rest of the code ...
func startStream() {
  streamTask = Task {
	  do {
		  for try await message in conversation.streamMessages() {
			  let content: String = try message.content()
			  print("Received message: \(content)")
			  await MainActor.run {
				  messages.append(message)
			  }
		  }
	  } catch {
		  print("Error in message stream: \(error)")
	  }
     }	
}
// Rest of the code ...
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { in
 streamTask?.cancel()
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { in
  Task{
    await loadMessages()
    startStreamTask()
  }
}

In this code:

  1. We listen for the UIApplication.willResignActiveNotification notification. When this notification is received, indicating the app is moving to the background, we cancel the streamTask, effectively stopping the stream.

  2. We also listen for the UIApplication.willEnterForegroundNotification notification. When this notification is received, indicating the app is moving to the foreground, we create a new task that loads the messages and starts the stream again.

This approach ensures that the stream is properly managed when the app transitions between the foreground and background states, preventing it from 'dying' silently without errors.

@humanagent humanagent requested a review from a team as a code owner December 6, 2023 15:39
@humanagent
Copy link
Contributor Author

humanagent commented Dec 6, 2023

Added a method for starting the app from a private key for faster testing

func dataFromHexString(_ hex: String) -> Data? {
    var data = Data(capacity: hex.count / 2)
    var buffer = 0
    var index = 0
    for char in hex {
        if let value = char.hexDigitValue {
            if index % 2 == 0 {
                buffer = value << 4
            } else {
                buffer |= value
                data.append(UInt8(buffer))
            }
            index += 1
        } else {
            return nil
        }
    }
    return data
}
func generateWalletWithPrivateKeys() {
    Task {
        do {
	    let privateKeyString = "key" // Your PrivateKey instance here
            // Function to convert hex string to Data
            
            
            if let privateKeyData = dataFromHexString(privateKeyString) {
				let privateKey = try PrivateKey(privateKeyData)
            let client = try await Client.create(account: privateKey, options: ClientOptions(api: .init(env: .production)))
            
			
            print(client.address)
            let keysData = try client.privateKeyBundle.serializedData()
            Persistence().saveKeys(keysData)

            await MainActor.run {
                self.status = .connected(client)
            }
			} else {
				// Handle the error case where the hex string couldn't be converted to Data
			}
           
            
        } catch {
            await MainActor.run {
                self.status = .error("Error generating wallet: \(error)")
            }
        }
    }
}

@humanagent humanagent changed the title Disconnect stream on background Disconnect and reconnect stream on background Dec 6, 2023
@humanagent humanagent self-assigned this Dec 23, 2023
@humanagent humanagent closed this Dec 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants