Download pictures from swift into typescript with the help of share extensions

Currently, I am working on setting up Share Extensions in my ionic3 application.

To begin with, I followed these steps:

Firstly, I built the app and then launched it in Xcode. After that, I added a Share Extension by navigating to File -> New -> Target -> Share Extension.

Subsequently, I referred to the documentation available at this link: Share Extension in ios.

After locating the ShareViewController.swift file, I made the following modifications:

override func didSelectPost() {
        if let item = self.extensionContext?.inputItems[0] as? NSExtensionItem{
            for ele in item.attachments!{
                let itemProvider = ele

                if itemProvider.hasItemConformingToTypeIdentifier("public.jpeg"){
                    NSLog("itemprovider: %@", itemProvider)
                    itemProvider.loadItem(forTypeIdentifier: "public.jpeg", options: nil, completionHandler: { (item, error) in

                        var imgData: String!

                        if let img = item as? UIImage{
                            imgData = img.pngData()?.base64EncodedString(options: <#T##Data.Base64EncodingOptions#>)
                        }

                        let dict: [String : Any] = ["imgData" :  imgData, "name" : self.contentText]
                        let userDefault = UserDefaults.standard

                        userDefault.set(dict, forKey: "img")
                        userDefault.synchronize()
                    })
                }
            }
        }
        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)

    }

The Share view Controller file can be found at:

./platforms/ios/shareItems/ShareViewController.swift

My ultimate goal is to transfer the images selected from the gallery to my app and retrieve them on a specific typescript page named login.ts located at:

.src/pages/login/login.ts

I need guidance on how to create functions to accomplish this task effectively.

Your assistance will be highly appreciated.

.

Answer №1

To start, the initial step is to retrieve images and text information from UserDefaults by utilizing the code snippet below.

let userDefault = UserDefaults.standard
        userDefault.addSuite(named: "group.yudiz.shareKitDemo")

        if let dict = userDefault.value(forKey: "img") as? NSDictionary{

            let data = dict.value(forKey: "imgData") as! Data
            let str = dict.value(forKey: "name") as! String

            self.imgView.image = UIImage(data: data)
            self.lblText.text = str

            userDefault.removeObject(forKey: "img")
            userDefault.synchronize()
        }

Furthermore, if there's a necessity to transmit an image as base64 encoded, the subsequent function can be employed.

// Start by converting the image to Data
let imageData = image.pngData()!
// Then convert the Data to base64 encoding    
let strBase64:String = imageData.base64EncodedString(options: .lineLength64Characters)

In addition, for decoding the base64 string into an image format, refer to the provided code snippet below.

let dataDecoded:Data = Data(base64Encoded: strBase64, options: NSData.Base64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to integrate ag-grid with Observable in Angular 2?

After conducting extensive research on the Internet, I am still struggling to connect the pieces. My angular2 application utilizes an Observable data source from HTTP and I am attempting to integrate ag-grid. However, all I see is a loading screen instead ...

Transforming the date from JavaScript to the Swift JSON timeIntervalSinceReferenceDate structure

If I have a JavaScript date, what is the best way to convert it to match the format used in Swift JSON encoding? For example, how can I obtain a value of 620102769.132999 for a date like 2020-08-26 02:46:09? ...

Expanding Arrays in TypeScript for a particular type

There is a method to extend arrays for any type: declare global { interface Array<T> { remove(elem: T): Array<T>; } } if (!Array.prototype.remove) { Array.prototype.remove = function<T>(this: T[], elem: T): T[] { return thi ...

What is the method for accessing xiph.org audio codecs on iPhone/iOS devices?

I currently have music encoded in the Vorbis format and have started encoding some of my albums to the newer Opus format. Is there a way for me to transfer and listen to them on my iPhone? The xiph.org wiki mentions support for Vorbis is a "work in progres ...

The utilization of React.Component inheritance in TypeScript

In my attempt to develop a base class using React.Component and derive two classes from the base class, I have encountered an issue. Here is how I structured the classes: interface BaseItemProps { base_prop: string; } class BaseItem<P, T> exten ...

Injecting live data into an input field within a table using Angular 4

Trying to create a dynamic row table with input fields in all cells. The loaded data is static, and I'm facing issues adding more data in the view. However, the functionality to add and delete rows is working fine. I have experimented with ngModel and ...

Facing difficulty in accessing mongoose schema static method in TypeScript

I am currently facing an issue where I have a method called "findByToken()" defined in the model and implemented as a static method in the userSchema. However, in another part of my application, I am unable to access the method using: User.findByToken(tok ...

Typescript is throwing a fit because it doesn't like the type being used

Here is a snippet of code that I am working with: import { GraphQLNonNull, GraphQLString, GraphQLList, GraphQLInt } from 'graphql'; import systemType from './type'; import { resolver } from 'graphql-sequelize'; let a = ({Sy ...

You cannot assign void to a parameter expecting a function with no return value

I have been working on an angular application that was initially developed in Angular 2, then upgraded to versions 7 and 9, and now I'm attempting to migrate it to Angular 11. There is a function in my code that fetches the notification count for the ...

Tips for linking an IBOutlet and IBAction to a View Controller without relying on the Assistant editor

When working in Xcode, I often struggle with using the Assistant editor to make connections between elements in the Interface Builder and the View Controller code. The process seems straightforward according to the documentation, but in reality, it can be ...

Alert for any shift in the main task at hand

As a beginner in mobile development, I kindly ask for some understanding if I overlook any obvious details. My main objective now is to find a way to monitor a foreground task on both iOS and Android. To elaborate, I want my program to perform the followi ...

Understanding Typescript typings and npm packages can greatly improve your development workflow

I'm pleased to see that NPM has now included support for importing TypeScript type wrappers. However, I've noticed inconsistency in how these wrappers are maintained. For instance, when attempting to import "node-git" and "@types/node-git", I fou ...

Transform the appearance of a complex image by altering its color using CSS

In my quest to bring a unique functionality to life, I am looking to achieve the following: I want to layer two transparent images within a <div>: one representing an object and the other depicting a glowing effect around the object. When hovering ...

Select information from an array and store it within an object

I want to extract all objects from an array and combine them into a single object. Here is the current array data: userData = [ {"key":"firstName","checked":true}, {"key":"lastName","checked":true ...

Leveraging Leaflet or any JavaScript library alongside Typescript and webpack for enhanced functionality

Important: Despite extensive searching, I have been unable to find a resolution to my issue. My current endeavor involves developing a map library through the extension of leaflet. However, it appears that I am encountering difficulties with utilizing js ...

Generate random entries from an object based on specific criteria and append them to a fresh object using Typescript

Experimenting with Ionic2 and Typescript has been my recent focus. I have an object that contains various meals, calorie counts, and meal types (such as vegan). This is how the object looks: [ { "id":14093, "name":"Proteinshake mit Wasser ...

Having trouble testing a Flutter app on a real iPhone due to the 'Runner' installation error in Xcode 11.4

After upgrading Xcode to 11.4, I encountered an issue when attempting to test my flutter app on a physical device. An error message stating 'Unable to install "Runner"' appeared, with further details indicating that no code signature was found. M ...

Create a function that retrieves the value associated with a specific path within an object

I want to implement a basic utility function that can extract a specific path from an object like the following: interface Human { address: { city: { name: string; } } } const human: Human = { address: { city: { name: "Town"}}}; getIn< ...

The absence of the 'classes' property in the MUI component type is causing an issue in Typescript Material UI

Simply put, typescript is giving me a hard time by complaining about the missing property classes on every material-ui component. Essentially, Typescript requires the presence of the classes property in nearly all material-ui components. Here is the error ...

Ways to resolve the issue of the missing property 'ganttContainer' on the 'Gantt' type

I encountered an issue while trying to utilize the Gantt chart feature from the Dhtmlx library in TypeScript. The problem seems to stem from an error during the initialization of gantt. How can I go about resolving this? Below is the relevant code snippet: ...