I'm trying to implement the https callable functions from firebase to my IOS app, but when I call the function from my device I get the following error:
2023-02-18 19:40:38.701646-0600 Spaces[16235:3277636] Task <48F8CCDC-85B7-451F-9D00-FC93D93B7AFC>.<1> finished with error [-1007] Error Domain=NSURLErrorDomain Code=-1007 "too many HTTP redirects" UserInfo={NSLocalizedDescription=too many HTTP redirects, NSErrorFailingURLStringKey=https://accounts.google.com/v3/signin/rejected?continue=https://uc.appengine.google.com/_ah/conflogin?state%3D~AJKiYcHgSfXKmjn8R3F7NQNdJB-nW8eUS2Xxxojs23jJxTuoOb6Rt2tr-ooa5vw_yCMFz2P1PZUzwzuI-GSUDkbDWHqF-UQ30JQOejlBnzcpcSAKxl60g4hHYnHsvNyJBRHx2z4JxKohRxTwAGiL9ryos8HHOQp1_0GOfqHncrBjMwXXdHNJoWAXtJ4-bf7K3sfh32yXYxEIkKiTadJMenpzjDp4MCu8LbG5OXVXI1tXqAouERC_B4-JQA2esYzTGw704LdBdksK&dsh=S1057996816:1676770836995843&flowEntry=ServiceLogin&flowName=WebLiteSignIn&ifkv=AWnogHcLgDBo5gsyBrVbQJMIcoCwk3TXQujaljG27PM2wEBBNE0chcGuSa8bvjDtbyfz1Ii6UodjEw&rhlk=no&rrk=32, NSErrorFailingURLKey=https://accounts.google.com/v3/signin/rejected?continue=https://uc.appengine.google.com/_ah/conflogin?state%3D~AJKiYcHgSfXKmjn8R3F7NQNdJB-nW8eUS2Xxxojs23jJxTuoOb6Rt2tr-ooa5vw_yCMFz2P1PZUzwzuI-GSUDkbDWHqF-UQ30JQOejlBnzcpcSAKxl60g4hHYnHsvNyJBRHx2z4JxKohRxTwAGiL9ryos8HHOQp1_0GOfqHncrBjMwXXdHNJoWAXtJ4-bf7K3sfh32yXYxEIkKiTadJMenpzjDp4MCu8LbG5OXVXI1tXqAouERC_B4-JQA2esYzTGw704LdBdksK&dsh=S1057996816:1676770836995843&flowEntry=ServiceLogin&flowName=WebLiteSignIn&ifkv=AWnogHcLgDBo5gsyBrVbQJMIcoCwk3TXQujaljG27PM2wEBBNE0chcGuSa8bvjDtbyfz1Ii6UodjEw&rhlk=no&rrk=32, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <48F8CCDC-85B7-451F-9D00-FC93D93B7AFC>.<1>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <48F8CCDC-85B7-451F-9D00-FC93D93B7AFC>.<1>, NSUnderlyingError=0x28045b2a0 {Error Domain=kCFErrorDomainCFNetwork Code=-1007 "(null)"}}
Callable function:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
// const fcm = admin.messaging();
const db = admin.firestore();
exports.addNumbers = functions.https.onCall((data) => {
// [END addFunctionTrigger]
// [START readAddData]
// Numbers passed from the client.
const firstNumber = data.firstNumber;
const secondNumber = data.secondNumber;
// [END readAddData]
// [START addHttpsError]
// Checking that attributes are present and are numbers.
if (!Number.isFinite(firstNumber) || !Number.isFinite(secondNumber)) {
// Throwing an HttpsError so that the client gets the error details.
throw new functions.https.HttpsError('invalid-argument', 'The function must be called with ' +
'two arguments "firstNumber" and "secondNumber" which must both be numbers.');
}
// [END addHttpsError]
// [START returnAddData]
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: '+',
operationResult: firstNumber + secondNumber,
};
// [END returnAddData]
});
Call from device(IOS, Swift):
func callNumbers() {
DispatchQueue.global(qos: .background).async {
functions.httpsCallable("addNumbers").call(["firstNumber": 10, "secondNumber": 5]) { result, error in
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
}
// ...
}
if let data = result?.data {
print(data)
}
}
}
}
Does anyone know how I can fix this?
I'm trying to implement callable functions so that I can do important tasks from the server and not from the device.
Related
I'm using the slightly older React vpn module. Module name: react-native-ip-sec-vpn
In the case of Android, normal operation was confirmed, but the following problem occurred during the iOS process.
RNIpSecVpn.connect was called with 6 arguments but expects 5 arguments.
If you haven't changed this method yourself, this usually means that your versions of the native code and JavaScript code are out of sync. Updating both should make this error go away.
We have confirmed that the functions that do not receive parameters such as prepare and disconnect included in the module operate normally. However, an error occurs in the Connect part.
The problem code is below.
// RNIpSecVpn.swift
#objc
func connect(_ address: NSString, username: NSString, password: NSString, vpnType: NSString, mtu: NSNumber, findEventsWithResolver: #escaping RCTPromiseResolveBlock, rejecter: #escaping RCTPromiseRejectBlock) -> Void {
let vpnManager = NEVPNManager.shared()
let kcs = KeychainService()
vpnManager.loadFromPreferences { (error) -> Void in
if error != nil {
print("VPN Preferences error: 1")
} else {
let p = NEVPNProtocolIKEv2()
p.username = username as String
p.remoteIdentifier = address as String
p.serverAddress = address as String
kcs.save(key: "password", value: password as String)
p.passwordReference = kcs.load(key: "password")
p.authenticationMethod = NEVPNIKEAuthenticationMethod.none
p.useExtendedAuthentication = true
p.disconnectOnSleep = false
vpnManager.protocolConfiguration = p
vpnManager.isEnabled = true
let defaultErr = NSError()
vpnManager.saveToPreferences(completionHandler: { (error) -> Void in
if error != nil {
print("VPN Preferences error: 2")
rejecter("VPN_ERR", "VPN Preferences error: 2", defaultErr)
} else {
vpnManager.loadFromPreferences(completionHandler: { error in
if error != nil {
print("VPN Preferences error: 2")
rejecter("VPN_ERR", "VPN Preferences error: 2", defaultErr)
} else {
var startError: NSError?
do {
try vpnManager.connection.startVPNTunnel()
} catch let error as NSError {
startError = error
print(startError ?? "VPN Manager cannot start tunnel")
rejecter("VPN_ERR", "VPN Manager cannot start tunnel", startError)
} catch {
print("Fatal Error")
rejecter("VPN_ERR", "Fatal Error", NSError(domain: "", code: 200, userInfo: nil))
fatalError()
}
if startError != nil {
print("VPN Preferences error: 3")
print(startError ?? "Start Error")
rejecter("VPN_ERR", "VPN Preferences error: 3", startError)
} else {
print("VPN started successfully..")
findEventsWithResolver(nil)
}
}
})
}
})
}
}
}
Code exporting iOS native module
// RNIpSecVpnBridge.m
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#interface RCT_EXTERN_MODULE(RNIpSecVpn, RCTEventEmitter)
RCT_EXTERN_METHOD(prepare:(RCTPromiseResolveBlock)findEventsWithResolver rejecter:(RCTPromiseRejectBlock)rejecter)
RCT_EXPORT_METHOD(connect:(NSString *)address username:(NSString *)username password:(NSString *)password vpnType:(NSString *)vpnType mtu:(NSNumber *_Nonnull)mtu findEventsWithResolver:(RCTPromiseResolveBlock)findEventsWithResolver rejecter:(RCTPromiseRejectBlock)rejecter){}
RCT_EXTERN_METHOD(disconnect:(RCTPromiseResolveBlock)findEventsWithResolver rejecter:(RCTPromiseRejectBlock)rejecter)
RCT_EXTERN_METHOD(getCurrentState:(RCTPromiseResolveBlock)findEventsWithResolver rejecter:(RCTPromiseRejectBlock)rejecter)
RCT_EXTERN_METHOD(getCharonErrorState:(RCTPromiseResolveBlock)findEventsWithResolver rejecter:(RCTPromiseRejectBlock)rejecter)
#end
The code of the module in JavaScript
// index.d.ts
import { EmitterSubscription } from "react-native";
export declare enum VpnState {
disconnected = 0,
connecting = 1,
connected = 2,
disconnecting = 3,
genericError = 4
}
export declare enum CharonErrorState {
NO_ERROR = 0,
AUTH_FAILED = 1,
PEER_AUTH_FAILED = 2,
LOOKUP_FAILED = 3,
UNREACHABLE = 4,
GENERIC_ERROR = 5,
PASSWORD_MISSING = 6,
CERTIFICATE_UNAVAILABLE = 7,
UNDEFINED = 8
}
export declare const STATE_CHANGED_EVENT_NAME: string;
export declare const removeOnStateChangeListener: (stateChangedEvent: EmitterSubscription) => void;
export declare const onStateChangedListener: (callback: (state: {
state: VpnState;
charonState: CharonErrorState;
}) => void) => EmitterSubscription;
export declare const prepare: () => Promise<void>;
export declare const connect: (address: string, username: string, password: string, vpnType?: string, mtu?: number) => Promise<void>;
export declare const getCurrentState: () => Promise<VpnState>;
export declare const getCharonErrorState: () => Promise<CharonErrorState>;
export declare const disconnect: () => Promise<void>;
declare const _default: any;
export default _default;
code in development
// home.tsx
async function startOvpn(state: Boolean) {
if (state) {
disconnect();
networkStateDetail();
} else {
try {
await connect(
networkInfoList[locationNum].address,
networkInfoList[locationNum].username,
networkInfoList[locationNum].password,
'none',
10,
);
networkStateDetail();
} catch (error) {
console.log(error);
}
}
}
I tried to fill in all the parameters required by the module and entered only the required parameters, but the same error occurs.
In RNIpSecVpn.swift and RNIpSecVpnBridge.m, which are the native codes of the module, the following error occurs when executed after processing #objc(connect :::::::).
Exception 'connect:username:password:vpnType:mtu:findEventsWithResolver:rejecter: is not a recognized Objective-C method.' was thrown while invoking connect on target RNIpSecVpn with params (
"1.1.1.1",
123,
123,
none,
10,
1400,
562,
563
)
Also, the code of IpSecVpnBridge.m was used as the existing RCT_EXTERN_METHOD, and the same error occurs even after modifying it with RCT_EXPORT_METHOD... Please help.
I modified the method export part of RNIpSecVpnBridge.m and changed the existing RCT_EXTERN_METHOD to RCT_EXPORT_METHOD(...){}, but the same error occurs.
After executing Clean (Ctrl + Shift + K) in xCode, pod install, npm run ios were executed, but the same error occurred
Even if you change the target ios version in node_module to 12 and run it, the same error occurs
I added #objc(connect :::::::) in RNIpSecVpn.swift but got another error.
It was identified as a NodeModule that implemented function execution using React native Module, and it seems to have been developed according to the format mentioned in the React-native formula. I can't find the cause and problem of the error. Help...
I am developing app with video calling functionality and I am using Twilio Video for that.
Currently using TwilioVideo SDK v4.6.2 and iOS Version 14.x and Above
I am not able to connect to the TwilioVideo room
Below is my code:
func connect() {
guard let accessToken = self.accessToken, let roomName = self.roomName else {
return
}
prepareAudio()
prepareCamera()
let connectOptions = ConnectOptions(token: accessToken) { (builder) in
builder.isDominantSpeakerEnabled = true
builder.isNetworkQualityEnabled = true
if let localAudioTrack = self.localAudioTrack {
builder.audioTracks = [localAudioTrack]
}
if let localVideoTrack = self.localVideoTrack {
builder.videoTracks = [localVideoTrack]
}
if let preferredAudioCodec = TwiloVideoSettingsManager.shared.audioCodec {
builder.preferredAudioCodecs = [preferredAudioCodec]
}
if let preferredVideoCodec = TwiloVideoSettingsManager.shared.videoCodec {
builder.preferredVideoCodecs = [preferredVideoCodec]
}
if let encodingParameters = TwiloVideoSettingsManager.shared.getEncodingParameters() {
builder.encodingParameters = encodingParameters
}
builder.region = "gll"
builder.roomName = roomName
}
self.room = TwilioVideoSDK.connect(options: connectOptions, delegate: self)
UIApplication.shared.isIdleTimerDisabled = true
}
Response in not received from Twilio in either of the methods mentioned below
func didConnect(to room: Room) {
NSLog("Room: \(room.name) SID: \(room.sid)")
if (room.remoteParticipants.count > 0) {
self.remoteParticipant = room.remoteParticipants[0]
self.remoteParticipant.delegate = self
}
self.delegate.videoServiceManagerDidConnectToRoom(name:room.name)
}
func roomDidFailToConnect(room: Room, error: Error) {
NSLog("Failed to connect to a Room: \(error).")
self.delegate.videoServiceManagerFailToConnectRoom(error: error.localizedDescription)
self.leaveRoom()
}
I am not able connect to the room every time and sometimes I get the error mentioned below :
Failed to connect to a Room: Error Domain=com.twilio.video Code=53000 "Signaling connection error" UserInfo={NSLocalizedDescription=Signaling connection error, NSLocalizedFailureReason=SIP error 408}.
When I check the Twilio logs in debug mode I am not getting any error.
Please guide me to rectify if there is any mistake in my code
Twilio employee here. Error 53000 is somewhat vague and could occur due to different things: https://www.twilio.com/docs/api/errors/53000
I'd suggest the following next steps:
try reproducing this error using the iOS Quickstart app (https://github.com/twilio/video-quickstart-ios)
try running our Networktest on the problematic device: https://www.networktest.twilio.com
I am getting an error time to time while making requests,
Optional(Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <BB6171AF-E4AF-49F2-ACEE-A2CDA67B825E>.<3>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <BB6171AF-E4AF-49F2-ACEE-A2CDA67B825E>.<3>",
"LocalDataPDTask <BB6171AF-E4AF-49F2-ACEE-A2CDA67B825E>.<3>",
"LocalDataTask <BB6171AF-E4AF-49F2-ACEE-A2CDA67B825E>.<3>"
), NSLocalizedDescription=The network connection was lost., _kCFStreamErrorDomainKey=4, NSErrorFailingURLStringKey=https://url, NSErrorFailingURLKey=https://url})
Why am I getting this error?
I have a method which handles api calls called retry() and depending on the status i need to refresh my token and then retry the same request again. So what I have done is check whether the response after excuting the initial api call is SOMECODE and then refresh the access token if it is calling the refreshAccessToken method and depending on its response if it's a success then I recursively call the same function retry() again and excute the logic. It works fine sometimes and sometimes it gives the above error. The code which performs the above operation is posted below,
if responseDescDisplay == "SOMECODE"{
refreshAccessToken(){ isSuccess,isFailed, errCode in
if isSuccess {
retry(urlString: urlString, method: method, requestBody: requestBody, completionHandler: completionHandler)
performRetry = true;
}else{
if !performRetry {
if errCode.isEmpty {
completionHandler(nil,nil,"OHNO");
}else{
completionHandler(nil,nil,"ERROR");
}
}
}
My access token refreshing method looks something like this,
URLSession.shared.dataTask(with: tokenRegenerateRequest) { data, res, err in
print("EROR: ", err)
print("DARA: ", data)
if err != nil {
print("IN HERE")
completionHandler(false, false, "INTERNAL_SERVER_ERROR");
}
guard let data = data, err == nil else {return}
guard let httpResponse = res as? HTTPURLResponse else {
return
}
// print("REGENRATING TOKEN \(httpResponse.statusCode) \(res)");
if httpResponse.statusCode == 200 {
if !data.isEmpty {
do {
let decodedResponse = try! JSONDecoder().decode(RefreshTokenResponse.self, from: data);
print("ACCESS TOKEN REGENRATE REQUEST: ", decodedResponse)
if !decodedResponse.accessToken.isEmpty && !decodedResponse.refreshToken.isEmpty {
completionHandler(true,false, "")
} else {
print("HERE1")
completionHandler(false,true,"")
}
}catch{
print("HERE2")
completionHandler(false,true,"")
}
} else {
print("HERE3")
completionHandler(false,true,"")
}
}else {
print("HERE4", httpResponse.statusCode)
completionHandler(false,true,"")
}
}.resume()
What am i doing wrong. Why do I keep getting the above error? Please can anyone post/suggest a possible way to overcome this issue? Please don't suggest to use any other libraries since I am stick to URLSession. Thanks in advance.
I am having an issue in the following swift code, using Parse-Server to save data online.
let xxDico = ["N8": "Eight", "N5": "Five"],
upLoadParseUnit = PFObject(className: "numberClass",
dictionary: xxDico)
print("xxDico : \(xxDico.count)")
upLoadParseUnit.saveInBackground {
(succeeded:Bool, error:Error?) in
if succeeded {
print("\(#function) succeeded!!")
} else {
if error?.localizedDescription == "NAME-USED" {
// A record previously existed with the same name.
print("\(#function) did not succeeded!!\nError: \(error?.localizedDescription)")
return
}
print("Error(1) in \(#function)\n" + (error?.localizedDescription)!)
}
}
And this is what I get in the debugging console:
xxDico : 2
Error(1) in executeUpLoad(_:)
The data couldn’t be read because it isn’t in the correct format.
This seems simple, but what am I doing wrong to get this error?
And what am I supposed to do?
Just working with Quick blox Chat API though its interesting and fun but stuck horribly when coming to sending messages successfully to group.
I first created a ChatDialog(not public group) and its created with out any problems.Now i want to send messages to the ChatDialog.
This is the code at Client side in Swift :
let user = QBUUser()
user.ID = (QBSession.currentSession().currentUser?.ID)!
user.password = "*********"
QBChat.instance().connectWithUser(user) { (error: NSError?) -> Void in
if error == nil{
print("Success in connection")
self.chatGroup = QBChatDialog(dialogID:self.selectedChatGroup.chatGroupId, type: QBChatDialogType.Group)
self.chatGroup.occupantIDs = self.selectedChatGroup.opponents
self.chatGroup.joinWithCompletionBlock { (err) in
if err == nil{
print("Joined Succesfully")
let message: QBChatMessage = QBChatMessage()
message.text = "PRAISE THE LORD"
message.deliveredIDs = [(QBSession.currentSession().currentUser?.ID)!]
message.readIDs = [(QBSession.currentSession().currentUser?.ID)!]
message.markable = true
self.chatGroup.sendMessage(message, completionBlock: { (error: NSError?) -> Void in
if err == nil{
print(message.text)
print("Message sent Succesfully")
let resPage = QBResponsePage(limit:20, skip: 0)
QBRequest.messagesWithDialogID(self.selectedChatGroup.chatGroupId, extendedRequest: nil, forPage: resPage, successBlock: {(response: QBResponse, messages: [QBChatMessage]?, responcePage: QBResponsePage?) in
print("Messages count is \(messages?.count)")
}, errorBlock: {(response: QBResponse!) in
})
}else{
print(err?.localizedDescription)
}
});
}
else{
print(err?.localizedDescription)
}
}
}
}
This is the Response that i am getting back.i am pretty sure that logging to chat, connecting to group are successful. Even from the response given back from the API is also affirming that sending message is successful.But i am not able to see any messages in the Admin Panel at Quick blox. And also tried getting all the messages from the Chat dialog but its giving 0 messages.So my messages are not getting delivered.
Yah, got the solution from Quickblox API.This is what i missed in my code.
var params = NSMutableDictionary()
params["save_to_history"] = true
message.customParameters = params
Worked like a charm!