Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

How to save file with Capacitor on iOS?

I have the following code (adapted from this tutorial) that I use for saving files from backend:

import { FilesystemDirectory, Plugins } from '@capacitor/core';
const { Filesystem } = Plugins;

await Filesystem.writeFile({
    path: "filename.txt",
    data: "base64 data",
    directory: FilesystemDirectory.Documents,
  });

This codes works fine on Android, even creates the Documents directory in the root of internal storage. Unfortunately, on iOS no file is created, no mater what directory I use (I've tested it with Documents, Data and ExternalStorage). When I put this code block inside try..catch, nothing is thrown, so the operation is supposedly completed successfully, just no file is saved. Tested on one Android device and two iOS.

How to Implement Deep Linking in Angular for iOS without Extension (.json) in URL Access?

I'm working on implementing deep linking in my Angular application for Flutter iOS, but I'm facing two main challenges. Firstly, I'm unable to access a JSON file without the .json extension. Secondly, I'm unsure how to properly set up deep linking in Angular for iOS. Can anyone provide guidance on resolving these issues?

Issues:

  • Accessing JSON file without .json extension: When attempting to access a JSON file without the .json extension in Angular, I'm encountering server configuration issues or Angular's default behavior. How can I resolve this?

  • Deep Linking in Angular for iOS: I need assistance in setting up deep linking in my Angular application specifically for iOS. What steps are involved in implementing this?

For more info I need to be make it below like

https://docs.flutter.dev/cookbook/navigation/set-up-universal-links#apple-app-site-association

[iOS]FCMを用いたプッシュ通知を、以前の HTTP から HTTP v1 に移行する方法について [closed]

以前の HTTP から HTTP v1 に移行するために、サーバーキーではなく、OAuth 2.0 アクセス トークンが必要になりました。 ただ、この取得方法がわかりません。

旧 Authorization: key=AIzaSyZ-1u...0GBYzPu7Udno5aA 新(↓これを取得したい) Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA

swiftでコーディングしたいのですが、どうしたら良いでしょうか?

秘密鍵をダウンロードし、OAuth2のアクセストークンを取得しようとしたのですが、クライアントIDはあっても、クライアントシークレットの情報がなく、できませんでした。

Fetch API Returns Empty Array in Next.js Despite Working API Endpoint

I'm using fetch() to retrieve data from my backend API in a Next.js project, but an empty array [] is always returned instead of the expected data. I've verified that the API is working correctly by testing it in a browser or using a tool like Postman. However, when I try to fetch the data in my Next.js component using the following code:

const BookList = async () => {
  const response = await fetch("http://localhost:3001/api/books");
  if (!response.ok) {
    throw new Error("Failed to fetch data");
  }
  const books = await response.json();
  console.log(books);

axios() is working perfectly but i want to use fetch() as it is recommended to use it in Next.js. What could be causing this issue, and how can I fix it to retrieve the correct data in my Next.js component?

[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write

When I run the code, I get the error ---------------------- "[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write". ----------------------

class BaseAPI<T: TargetType> {
    
    func fetchData<M: Decodable>(target: T, responseClass: M.Type, completion:@escaping(Result<M?, NSError>) -> Void) {
        let method = Alamofire.HTTPMethod(rawValue: target.methods.rawValue)
        let headers = Alamofire.HTTPHeaders(target.headers ?? [:])
        let params = buildParams(task: target.task)
        AF.request(target.baseUrl + target.path, method: method, parameters: params.0, encoding: params.1, headers: headers).responseDecodable(of: M.self) { response in
            guard let statusCode = response.response?.statusCode else {
                //ADD Custom Error
                completion(.failure(NSError()))
                return
            }
            if statusCode == 200 {
                // Successful Request
                guard let jsonResponse = try? response.result.get() else {
                    completion(.failure(NSError()))
                    return
                }
                guard let theJSONData = try? JSONSerialization.data(withJSONObject: jsonResponse, options: []) else {
                    completion(.failure(NSError()))
                    return
                }
                guard let responseObj = try? JSONDecoder().decode(M.self, from: theJSONData) else {
                    completion(.failure(NSError()))
                    return
                }
                completion(.success(responseObj))
                
            } else {
                completion(.failure(NSError()))
            }
        }
        
        
    }
    
    private func buildParams(task: Task) -> ([String:Any], ParameterEncoding) {
        switch task {
            
        case .requestPlain:
            return ([:], URLEncoding.default)
        case .requestParameters(parameters: let parameters, encoding: let encoding):
            return (parameters, encoding)
        }
    }
}

instead of try? JSONSerialization.data(withJSONObject: jsonResponse, options: []) When I try the try? JSONSerialization.data(withJSONObject: jsonResponse, options: []) code, it gives the error No exact matches in call to class method 'jsonObject'.

Building for 'iOS-simulator', but linking in object file (xxx/libmp3lame.a[arm64][2](VbrTag.o)) built for 'iOS'

Why the lame library I compiled cannot be started through the simulator on the iOS project,I tried exclude arm64 in other methods but no luck,those cann't fix this bug and create more error.A little earlier,this app can run in simulator and real device,now it just run in real device.Rosetta is useful,but rosetta is treating the symptoms rather than the root cause and simulator become laggy.lipo info for lame in my project is 'armv7 armv7s x86_64 arm64'

I tried exclude architectures,but it will cause more errors because the package my pod uses.It can be opened using rosetta, but it is very laggy. The device I am using is a MacBook Air with m1 chip. I have the need to collaborate with colleagues on development, and using rosetta for a long time is also an unreasonable method.

UIButton color not restored to original color

I am making a quiz app. Its button colour changes if clicked based on correct or wrong answer. But I want to restore the color to the original one after some delay. The color is changed but not restored to the default after the delay of 0.2 seconds.

Here is my code:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var questionLabel: UILabel!
    @IBOutlet weak var progressBar: UIProgressView!
    @IBOutlet weak var falseButton: UIStackView!
    @IBOutlet weak var trueButton: UIStackView!

    var QuestionNumber=0
    var score=0
    var questionArray = [
        Question(q: "A slug's blood is green.", a: "True"),
        Question(q: "Approximately one quarter of human bones are in the feet.", a: "True"),
        Question(q: "The total surface area of two human lungs is approximately 70 square metres.", a: "True"),
        Question(q: "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home to eat.", a: "True"),
        Question(q: "In London, UK, if you happen to die in the House of Parliament, you are technically entitled to a state funeral, because the building is considered too sacred a place.", a: "False"),
        Question(q: "It is illegal to pee in the Ocean in Portugal.", a: "True"),
        Question(q: "You can lead a cow down stairs but not up stairs.", a: "False"),
        Question(q: "Google was originally called 'Backrub'.", a: "True"),
        Question(q: "Buzz Aldrin's mother's maiden name was 'Moon'.", a: "True"),
        Question(q: "The loudest sound produced by any animal is 188 decibels. That animal is the African Elephant.", a: "False"),
        Question(q: "No piece of square dry paper can be folded in half more than 7 times.", a: "False"),
        Question(q: "Chocolate affects a dog's heart and nervous system; a few ounces are enough to kill a small dog.", a: "True")
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        //fill the current question on screem
        updateUI()
    }
    
    @IBAction func answerButtonPressed(_ sender: UIButton) {
        // checking question not going to out of bound
        if QuestionNumber + 1 < questionArray.count
        {
            let userAnswer = sender.currentTitle
            
            let actualAnswer = questionArray[QuestionNumber].answer
           
            if userAnswer == actualAnswer
            {   // change the backgroundcolor
                sender.backgroundColor=UIColor.green
                score+=1
            }
            else
            {   sender.backgroundColor=UIColor.red
                score-=1
            }
            QuestionNumber+=1
            // let some delay  0.2sec 
            Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(updateUI), userInfo: nil, repeats: false)
           
        }
       else
        {
           questionLabel.text="Done. Your score is \(score)"
           print(score)
          
       }
    }

    @objc func updateUI()
    {
        questionLabel.text=questionArray[QuestionNumber].text
        trueButton.backgroundColor=UIColor.clear
        falseButton.backgroundColor=UIColor.clear
        
        print("color changed")
    }
}

idb & Ffmpeg hls video is taking lot of time to start creating video

I'm trying to capture a simulator's screen using idb & ffmpeg with the command

idb video-stream --fps 15 --format h264 --compression-quality 1.0 --udid <UDID> | ffmpeg -i pipe:0 -vcodec libx264 -threads 1 -crf 40 -preset ultrafast -f hls -g 30 -hls_list_size 0 -hls_time 5 -r 15 ./index.m3u8

This is taking around 15s to create the index.m3u8 file resulting in the loss of first 15 seconds of video. I've tried adding

-tune zerolatency

but this too has no effect. Idb starts video streaming right away on its own. Need help triaging why ffmpeg is processing it so late. The output ffmpeg provides when it eventually starts writing to ts files

Input #0, h264, from 'pipe:0':
  Duration: N/A, bitrate: N/A
    Stream #0:0: Video: h264 (High), yuvj420p(pc, progressive), 1178x2556, 25 fps, 25 tbr, 1200k tbn, 50 tbc

ffmpeg -version

ffmpeg version N-92246-gc2ac3b8e6a-tessus  https://evermeet.cx/ffmpeg/  Copyright (c) 2000-2018 the FFmpeg developers
built with Apple LLVM version 10.0.0 (clang-1000.11.45.2)
configuration: --cc=/usr/bin/clang --prefix=/opt/ffmpeg --extra-version=tessus --enable-avisynth --enable-fontconfig --enable-gpl --enable-libaom --enable-libass --enable-libbluray --enable-libfreetype --enable-libgsm --enable-libmodplug --enable-libmp3lame --enable-libmysofa --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopus --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libx264 --enable-libx265 --enable-libxavs --enable-libxvid --enable-libzimg --enable-libzmq --enable-libzvbi --enable-version3 --pkg-config-flags=--static --disable-ffplay
libavutil      56. 19.101 / 56. 19.101
libavcodec     58. 33.102 / 58. 33.102
libavformat    58. 19.102 / 58. 19.102
libavdevice    58.  4.106 / 58.  4.106
libavfilter     7. 37.100 /  7. 37.100
libswscale      5.  2.100 /  5.  2.100
libswresample   3.  2.100 /  3.  2.100
libpostproc    55.  2.100 / 55.  2.100

Game Center quick match error: failed to find players

My simulator shows this error alert (failed to find players) immediately after I click the quick match option. On my real phone this alert is never shown. How can I fix this in order to actually test my app?

Edit: I have tried both, a sandbox account and an actual (real) apple id.

Why is a CALayer retained after I stop referencing it?

I've the impression that my CALayer is retained after being added as a sublayer until the end execution block, instead of until I stop referencing it. The parent UIView is however released as soon as it is de-referenced as expected.

class DebugCALayer: CALayer {
  let id: String
  init(_ id: String) {
    self.id = id
    print("DebugCALayer init \(id)")
    super.init()
  }

  required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }

  deinit { print("DebugCALayer deinit \(id)") }
}

class DebugUIView: UIView {
  private let id: String
  init(_ id: String) {
    print("DebugUIView init \(id)")
    self.id = id
    super.init(frame: .zero)
    layer.addSublayer(DebugCALayer(id))
  }

  required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") }

  deinit { print("DebugUIView deinit \(id)") }
}

This can be tested with this code:


final class CALayerReleaseTests: XCTestCase {
  override func setUp() async throws {
    print("setup")
  }

  override func tearDown() {
    print("tear down")
  }

  func testBaseline() throws {
    for i in 0..<2 {
      _ = DebugUIView("\(i)")
    }
  }
}

which logs

setup
init DebugUIView 0
init DebugCALayer 0
deinit DebugUIView 0
init DebugUIView 1
init DebugCALayer 1
deinit DebugUIView 1
tear down
deinit DebugCALayer 1
deinit DebugCALayer 0

The release cycle for the UIView is as expected, with instances being de-inititalized as soon as I am not referencing them. However the CALayers remain referenced until after the test is teared-down.

If I now exit the main thread right after de-referencing my instance, the memory is deallocated correctly:

  func testDispatch() throws {
    for i in 0..<2 {
      _ = DebugUIView("\(i)")
      let exp = expectation(description: "")
      DispatchQueue.main.async {
        exp.fulfill()
      }
      waitForExpectations(timeout: 1)
    }
  }

logs

setup
init DebugUIView 0
init DebugCALayer 0
deinit DebugUIView 0
deinit DebugCALayer 0
init DebugUIView 1
init DebugCALayer 1
deinit DebugUIView 1
deinit DebugCALayer 1
tear down

My guess from those observations is that calling addSublayer has a retaining side effect on the layer that lasts until the end of the current execution block on the main thread. I was surprised to see this and was curious to understand what is exactly happening.

Note: running the same code in the Playground gives yet another result...

how to segregate authanticated and unauthanticated routes in the react with react-router-dom

this is my 'routes.tsx' file where all i simply want to do is if user is not authenticated then he/she should not able to navigate into dashboard and other routes which will comes into app later. and if he is authenticated then he/she should not navigate to unauthenticated routes which are login , signup , confirm otp there could be more also. for now isAuthenticated function is only returning if local storage has token or not in boolean. this is also looks good but there are some issues in this code which i am facing like

  • even after token is there in the local storage if user tries to navigate to any auth related route he is able to navigate there.
  • one more thing which i want to implement here with 'axios' intercepter that if user manually removes token and then try to run any api then in the interceptor should check if local storage has no token then interceptor should clear storage and then navigate user back to the auth/login

expecting a simple and optimal flow for the authenticated and vice versa routes and with the interceptor 'axios' without refreshing app

import { Suspense } from "react";
import { Navigate, RouteObject } from "react-router-dom";
import { isAuthenticated } from "./auth";
import { Login, Dashboard, Signup, SendOTP } from "../pages";
import { AuthLayout, PrimaryLayout } from "../layouts";

export const routes: RouteObject[] = [
  {
    path: "/dashboard",
    element: (
      <Suspense fallback={<div>...LOADING</div>}>
        {isAuthenticated() ? (
          <PrimaryLayout />
        ) : (
          <Navigate to="/auth/login" replace />
        )}
      </Suspense>
    ),
    children: [
      {
        index: true,
        element: <Dashboard />,
      },
      { path: "*", element: <Navigate to="dashboard" replace /> },
    ],
  },
  {
    path: "/auth",
    element: <AuthLayout />,
    children: [
      {
        index: true,
        element: isAuthenticated() ? (
          <Navigate to="/dashboard" replace />
        ) : (
          <Navigate to="login" replace />
        ),
      },
      {
        path: "login",
        element: (
          <Suspense fallback={<div>...LOADING</div>}>
            <Login />
          </Suspense>
        ),
      },
      {
        path: "signup",
        element: (
          <Suspense fallback={<div>...LOADING</div>}>
            <Signup />
          </Suspense>
        ),
      },
      {
        path: "confirm-otp",
        element: (
          <Suspense fallback={<div>...LOADING</div>}>
            <SendOTP />
          </Suspense>
        ),
      },
      { path: "*", element: <Navigate to="/auth/login" replace /> },
    ],
  },
  {
    path: "*",
    element: isAuthenticated() ? (
      <Navigate to="/dashboard" replace />
    ) : (
      <Navigate to="/auth/login" replace />
    ),
  },
];

SwiftUI - Grid/Table Layout for user input (Rows) -

Trying to make a SWiftUI layout, end goal will be to have it look sort of like a table view. Right now I am using a grid. Within the Grid are Rows of (usually) a Label(), and 3 TextFields(). This is my current code for it, right now it looks okay, however when i type in the textfields after a certain amount of character have been inputed it starts to expand the cut the label and other textfield out of site. Any advise?

Grid {
   // Basic Empty Weight Row
   GridRow {
      Label("Basic Empty", systemImage: "")
         .labelStyle(.titleOnly)
                            
      TextField("W", text: $basicEmpW)
      TextField("A", text: $basicEmpA)
      TextField("MOM", text: $basicEmpMOM)
   }
   .padding(.horizontal, 10)
   .fixedSize(horizontal: true, vertical: false)
                    
   // Pilot Row
   GridRow {
     Label("Pilot / Co-Pilot", systemImage: "star.fill")
        .padding(.horizontal, 10)
        .lineLimit(0)
                            
     TextField("W", text: $pcpW)
     TextField("A", text: $pcpA)
     TextField("MOM", text: $pcpMOM)
   }
   .padding(.horizontal, 10)
   .fixedSize(horizontal: true, vertical: false)
   .multilineTextAlignment(.center)
   
   // Zero Fuel Weight Row
   GridRow {
     Label("Zero Fuel", systemImage: "gym.bag.fill")
        Label(zerofW, systemImage: "gym.bag.fill")
   }
❌
❌