I am developing an app to select pictures from iPhone local gallery, after that pictures must be uploaded to firebase storage and they need to be converted into Data. I am working with SwiftUI and PhotosPickerItem form PhotosUI library. I need to complete this code:
private func photosPickerItemToData(_ photos: [PhotosPickerItem]) -> [Data] {
logger.log("photosPickerItemToData: \(photos.count)")
var data = [Data]()
for photo in photos {
}
}
Related
We have a native iOS app that has a Realm database. Now we have developed a new Flutter app that will substitute the native iOS app. When an user upgrade native iOS app to the new Flutter app, we want to migrate the existing Realm database content into the new Sqflite database.
We have created a Flutter plugin with swift to export Realm data to json. At the moment, we were able to add RealmSwift dependency to the plugin, but when we run the below code, it throws Cannot find 'DeviceModel' in scope.
Any idea to get all rows from DeviceModel table? To acomplish that is necesary to add some Realm schema manually?
import Flutter
import UIKit
import RealmSwift
enum PluginError: Error {
case notImplemented
}
public class SwiftRealmToJsonPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "realm_to_json", binaryMessenger: registrar.messenger())
let instance = SwiftRealmToJsonPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: #escaping FlutterResult) {
switch call.method {
case "getPlatformVersion":
result("iOS " + UIDevice.current.systemVersion)
case "realmInfoExist":
result(check_data())
default:
result(FlutterMethodNotImplemented)
}
}
// check if Realm exists
func check_data() -> Bool {
let realm = try! Realm()
let devices = realm.objects(DeviceModel.self)
}
}
The solution was:
Change plugin language from Swift to Objective-C and copy and paste all Realm models.
Implement in each model class a method to generate a dictionary with it data.
Export dictionary to json.
Right now we are able to export Realm info into a json format. Next step is implement the migration logic to adapt a table-less structure to sql.
Thanks to #Jay to point me out on the good direction to get a solution.
I am trying to share a custom struct between two users within the App via ShareLink (UIActivityViewController) in SwiftUI. I created a custom Document Type, the Exported Type Identifier and marked the struct as Transferable.
However, while I am able to save the example to a file, I would like to send it to another user via AirDrop or similar, s.t. the App appears as an Application Activity.
import SwiftUI
import UniformTypeIdentifiers
struct SwiftUIView: View {
#State private var customStruct: CustomStruct = CustomStruct()
var body: some View {
ShareLink(item: customStruct, preview: SharePreview(customStruct.name))
}
}
struct CustomStruct: Codable {
var name: String = "Test Example"
var description: String = "Test"
}
extension CustomStruct: Transferable {
static var transferRepresentation: some TransferRepresentation {
CodableRepresentation(contentType: .customStruct)
}
}
extension UTType {
static var customStruct: UTType { UTType(exportedAs: "com.TestExample.CustomStruct") }
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView()
}
}
Have you tried setting the "Conforms To" value in "Exported Type Identifiers" to public.json instead of public.data? After all, your custom struct conforms to Codable and can thus be serialized into JSON. For me this did the trick and Messages started showing up in the share sheet. When running on a device, I also see AirDrop.
What I’m still struggling with is how the receiving app can actually handle the file. I added the LSSupportsOpeningDocumentsInPlace key to Info.plist and set it to YES which causes the file to open in my app by tapping, but then I’m a bit stuck. Maybe onOpenURL: and decode the JSON file that the URL points to? I found zero results on the internet for this, which is a bit surprising.
I have a music app written in SwiftUI with some models (Song, Artist), and manager class (LibraryManager) which handles adding new song, generating playlist and serves as a player manager. The structure is like below.
class LibraryManager: ObservableObject {
#Published var songs: [Song] = []
#Published var artists: [Artist] = []
#Published var albums: [Album] = []
// Some methods here
}
// MainApp.swift - used to pass libraryManager into each view
let libraryManager = LibraryManager()
....
ContentView().environmentObject(libraryManager)
I recently want to implement CoreData to my app to store my models like Song. I don't want to change a lot of existing code, which means I still want to use the existing LibraryManager to handle these things. However, I found there is no way of using #FetchRequest in class. Any solutions? Or could anyone tell me the convention of the usage of CoreData.
I have an independent application on watchOS 6 and in my app I am using the Firestore REST API to show the data to the user using URLSession.
Since the Cloud Firestore REST API returns a JSON string, in order to process the data, I have created nested structs. Example: To access the 'title' in a particular response, I do something like this: response.mapValue.fields.title.stringValue.
The app works fine for now. In the long run I plan on creating the URLSessions as background tasks. Right now, I am calling URLSession every time the view is rendered by using .onAppear(functionToUseURLSession())) on my data's List view.
Now the next thing I want to implement is the complication for this particular app.
I am new to Swift and SwiftUI and am having the hardest time just getting started. All the tutorials I've been through online use WKExtensionDelegate to get the data models for the complication.
But in my case, I don't even have a data model! I just have structs calling other structs in a nested fashion in order to process the JSON response I get from the API call.
Any help allowing me to understand this is highly appreciated!
Here is some code to better understand the structure of the App:
struct Firebase: Codable {
var name: String?
var createTime, updateTime: String?
var fields: FirebaseFields
}
Now, FirebaseFields is also another struct:
struct FirebaseFields: Codable {
var emailID, lastName, firstName: String?
var goalsRoutines: GoalsRoutines
enum CodingKeys: String, CodingKey {
case emailID = "email_id"
case lastName = "last_name"
case firstName = "first_name"
}
}
Similarly, GoalsRoutines is also a struct...
As mentioned above, I have made these structs to follow the exact structure of the JSON object is get in response from Firebase API. So I access fields like: Firebase.FirebaseFields.GoalsAndRoutines.whatever.is.my.firebase.schema
My GoalsView.swift is:
var body: some View {
List{
...
...
}.onAppear{
FirebaseServices.getFirebaseData() {
(data) in self.data = data
}
}
}
And finally, in FirebaseServices.swift, func getFirebaseData is:
func getFirebaseData(completion: #escaping ([Value]) -> ()) {
guard let url = URL(string: "FIRESTORE URL HERE") else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
let data = try! JSONDecoder().decode(Firebase.self, from: data!)
DispatchQueue.main.async {
completion(data.fields.goalsRoutines.arrayValue.values)
}
}.resume()
}
So this is how I currently get the data and show it on the app.
I am really lost on how to do the same on my Complication.
Any help is really appreciated.
I cannot find documentation on the Parse.com table column Object data type. I assume it is an object in the context of software development. However, what is the syntax to use to enter an object into the object column? I would be interested to know both the programmatic steps to take (not too concerned about which language, more concerned about actions to take to save to the object column), but I would be even more interested to know how to enter an object into the table from the Parse.com website. Can we do this from the Data section of the "Core" tab, in the Parse.com Dev webpage for the app?
I did this little test in Swift to try and save an object with a property of type object (myCar) to the table from code (I have a Parse.com table with class name Test, which has an object column called myCar). It is causing an error (I'm new to iOS so cannot find out much about the error):
Car class
class Car {
var doors = 4
func addDoor() {
doors++
}
}
client code:
override func viewDidLoad() {
var testMan = PFObject(className:"Test")
var car = Car()
testMan["myCar"] = car //////////////// error here
testMan.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// The object has been saved.
println("Success")
} else {
// There was a problem, check error.description
println("Failure")
}
}
}
well, u're mixing swift objects with parse objects .. if you want a Car object linked to your Test class you must create it in parse database (+ add class -> car -> and then create properties in it). When you have created parse class Car u can use it in swift code as let car = PFObjecT(className: "Car") and later on assign that class to test object with testMan["myCar"] = car