Post marked as solved
152
Views
I am looking to integrate my code with CoreData. Presently I have the following of which allows a worker to check their requirements against an advert e.g. if the worker needs x3 sponges to clean a bathroom, then the advert must provide those sponges, but the worker can only work on set days:
var cdExample: [CleaningRota] = [bathroomMonday, kitchenFriday]	//
[Full sample code](https://developer.apple.com/forums/content/attachment/648c2166-46f3-44a3-bfc7-5e36f3d38721){: .log-attachment}
CORE DATA EXAMPLE
		let personAvailable: [Person] = [kath, mavis]
		//CORE DATA EXAMPLE : WORK ON OFFER
		for work in cdExample {
				//WORK TOOLS PROVIDED ON SITE
				for toolsAvailable in work.tool {
						//PERSONS AVAILABLE TO WORK
						for person in personAvailable {
								//PERSONAL REQUEST : SPECIFIC WORK DAY
								if person.avilability == work.day {
										//CHECK PERSON TOOL REQUIREMENTS FOR JOB
										for personRequirement in person.materialsNeeded {
												//CYCLE THROUGH TOOLS WORKER NEEDS ON SITE
												if personRequirement.tool == toolsAvailable.name {
														//CONFIRM TOOLS WORKER NEEDS ARE FULLY PROVIDED
														//AVOID CHECKING SAME STOCK TWICE IF CONDITION PREVIOUSLY MET
														if personRequirement.quantity <= toolsAvailable.stock && personRequirement.met == false {
																print(">>0> \(person.name)")
																print(">>1> \(personRequirement.tool) : \(personRequirement.quantity)")
																print(">>2> \(toolsAvailable.name) : \(toolsAvailable.stock)")
																personRequirement.met = true
																person.materialID.append(toolsAvailable.id)
														}
												}
										}
								}
						}
				}
		}
As the adverts and requirements pile up this kind of system will not scale very quickly. I would like to know if there is a better way to model this data, or to check conditions.
I plan to pull the cdExample from CoreData, and am unfamiliar with using it. Being a proprietary Apple Framework I do not know if anyone will help me here, but if not then how best to achieve what I want without a pyramid of doom (which I don't mind), is there a better way please?
I also need to remove the stock, which I ran into trouble with as I had too many loops and hit a bug in Xcode, so I think I'm doing something wrong with all of these loops ?
Post marked as solved
124
Views
Hello guys. I've been stuck two days with this issue, hope you can understand my question below because I'm still new with Swift.
I want to create a generic function that request some JSON data from an API, decode the response using the Codable protocol and save it in a @State variable to update the View
Here is what I've done so far.
struct Response: Codable {
var results: [Result]
}
struct Result: Codable {
var trackId: Int
var trackName: String
var collectionName: String
}
Here is the function
func loadData<T: Decodable>(model: T.Type) {
guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(model, from: data) {
DispatchQueue.main.async {
print(decodedResponse)
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}
.resume()
}
The thing is, so far I'm only able to print the response, but I can't do something like this:
DispatchQueue.main.async {
self.results = decodedResponse.results
}
Because it shows me this error Value of type 'T' has no member ' results'
Here is the View
struct TestView: View {
@State private var results = [Result]()
var body: some View {
List(results, id: \.trackId) { item in
VStack(alignment: .leading) {
Text(item.trackName)
.font(.headline)
Text(item.collectionName)
}
}
.onAppear {
loadData(model: Response.self)
}
}
// Here is the function defined
}
Somebody could give a hint? I really appreciate it
Thank you.
Dennis
Post marked as unsolved
47
Views
I have just fixed an issue where its solution was to move my code to different .swift files and then reference them as views in ContentView.swift. I have modal views in my new view swift files, using this repo - https://github.com/ViktorMaric/HalfModal, and now my Modal views show up as their own tab in my TabView, whereas they didn't before. My code is below...
ContentView.swift - https://developer.apple.com/forums/content/attachment/80e41ced-67a1-4083-8bbb-49d1e9caa610
rocketView.swift - https://developer.apple.com/forums/content/attachment/00da3f2e-0be2-4ec9-8eb5-c7131****48d
aboutView.swift - https://developer.apple.com/forums/content/attachment/e7e9d046-7637-48c0-aee5-8bb4fc43a278
launchesView.swift - https://developer.apple.com/forums/content/attachment/673078c5-6506-42ee-a150-f0f0db625afc
Post marked as solved
169
Views
I am trying to write my first app, after adding another item to tab view, I get the error
The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
How do I stop this error?
my code is:
my code - https://developer.apple.com/forums/content/attachment/30e42482-cc67-416a-b859-861c81bac7ff
Post marked as unsolved
53
Views
I create widget with temperature from my site. In standart program all work, but in Widget on result i see "0" (info from var)
Here code with mistake (DataProvider.swift)
import Foundation
class DataProvider {
		
		struct CurrencyJSON: Codable {
				var temp : String
		}
		static func getTemp() -> String {
				
		var dig : String = "0"
		print ("1")
		//on url this data: {temp:3.5}, this is my site, i can do anything format, may be make format: 3.5 (no json)?
		URLSession.shared.dataTask(with: URL(string: "http://example.com/weather.php")! ) {(data, response, error) in
				guard let data = data else { return }
				do {
						let res = try JSONDecoder().decode(CurrencyJSON.self, from: data)
						dig=res.temp
						print ("\(dig)")
				} catch let error {
						print("\(error)")
				}
		}.resume()
		return dig
		}
		
}
And on widget i see "0" (From this: var dig : String = "0"), why? Where i make mistake?
Here my struct Provider: TimelineProvider:
struct Provider: TimelineProvider {
		func placeholder(in context: Context) -> SimpleEntry {
				SimpleEntry(date: Date(), myString: "...")
		}
		func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
				let entry = SimpleEntry(date: Date(), myString: "...")
				completion(entry)
		}
		func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
				var entries: [SimpleEntry] = []
				print ("1")
				// Generate a timeline consisting of five entries an hour apart, starting from the current date.
				let currentDate = Date()
				for hourOffset in 0 ..< 5 {
						let entryDate = Calendar.current.date(byAdding: .second, value: hourOffset * 10, to: currentDate)!
						
						let entry = SimpleEntry(date: entryDate, myString: DataProvider.getTemp())
						entries.append(entry)
				}
				let timeline = Timeline(entries: entries, policy: .atEnd)
				completion(timeline)
		}
}
Post marked as unsolved
36
Views
Hi!
I am trying to publish a new version of my app which is build with Xamarin and i get this error: ITMS-90433 Invalid Swift Support, The file libswiftUIKit.dylib doesn't have the correct code signature. What can i do to submit my app build because i have tried to copy the .dylib file from my application files such as Framework folder inside my app archive or even from XCode's Swift folder, but it's not working.
If I don’t create the SwiftSupport folder and copy the libswiftUIKit.dylib file from another location, I get this error: ITMS-90424 Invalid Swift Support - The SwiftSupport folder is empty. It says that I should rebuild my app using the current GM version of Xcode but I can not build my app using XCode because I’m working with Xamarin so I have to use Visual Studio to build and to archive it for publishing.
When I build my app using Visual Studio it doesn’t generate the SwiftSupport folder and the files inside it.
Does anybody know how to solve this because i have tried almost everything that i read on internet.
Thank you in advance!
Post marked as unsolved
38
Views
i get 2 of these errors ""Cannot find 'application' in scope"" what am i doing wrong or why is it not in scope?
//
// ViewController.swift
// Diabell App
//
// Created by Richard Klug on 23/04/2021.
//
import UIKit
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//Function Email Bottom Left
@IBAction func Mail(_ sender: Any) {
showMailComposer()
}
func showMailComposer() {
guard MFMailComposeViewController.canSendMail() else{
return
}
let composer = MFMailComposeViewController()
composer.mailComposeDelegate = self
composer.setToRecipients(["richard.klug@diabell.se"])
composer.setSubject("Diabell App Help")
composer.setMessageBody("Fyll i vad du behöver hjälp med", isHTML: false)
present(composer, animated: true)
}
//Funktion Call Bottom Right
@IBAction func btnCallClick(_ sender: UIButton) {
if let phoneURL = URL(string: "tel://+46706106310"){
if application.canOpenUrl(phoneURL){
application.open(phoneURL, [:], completionHandler: nil)
}else{
}
}
}
}
Post marked as solved
33
Views
I have a string - "productRaw" which I am splitting up to show in separate sectionData cells, whilst under the same "Item 1" cellData table view. This is the code I am using to split up the String and add each separate part to a separate sectionData cell.
let group_array = document["product"] as? [String] ?? [""]
let productName1 = group_array.first ?? "No data to display :("
let productRaw = "\(productName1)"
let componentsRaw = productRaw.components(separatedBy: ", ")
var product = [String: String]()
for component in componentsRaw {
let keyVal = component.components(separatedBy: ": ")
product[keyVal[0]] = keyVal[1]
}
if let productName = product["Product Name"], let listingPrice = product["Listing Price"], let briefDescription = product["A brief description"], let productURL = product["Product URL"], let activeUntil = product["Listing active until"] {
self.tableViewData = [cellData(opened: false, title: "Item 1", sectionData: [productName], [listingPrice], [briefDescription], [productURL], [activeUntil])]
}
Where I am declaring the individual cells I want to be shown for the first section - "Item 1", when I only use [productName] in my sectionData then this compiles without any issues.
However when I also add , [listingPrice], [briefDescription], [productURL], [activeUntil] to my sectionData I receive the following error for the [cellData(opened: syntax.
Extra arguments at positions #4, #5, #6, #7 in call
So my question is, why am I receiving the above error and what can I do to resolve it?
Post marked as solved
107
Views
I am trying to open the swift file so that I can Ctrl + Drag from the image cell into the swift file that I generated.
The file was generated by New File - Cocao Touch class, previously.
With the main.storyboard open and then choosing Assistant, I get the ViewController.h for the scene I am in and not the ExploreCell.swift file that I have just generated.
The book I am following as I am a beginner, says that I should set the file as automatic but I can't seem to be able to do that.
What am I doing wrong?
Post marked as unsolved
756
Views
Hi, how do I make a button so that when it is pressed, it calls a phone number?
Post marked as unsolved
27
Views
Unicode values in cookies creating issue while loading the page url inside the iOS application.
Web view is failing every time while reading the cookies and return my web page to login screen.
Flow of app:
We are using Chinese characters in the user name. Once we launch the url in native app webpage, cookies contains the username with it as provided, but it converted to unicode which makes cookies corrupted.
Can anyone help me on this?
Thanks in advance.
Manoj
Post marked as solved
72
Views
Hi im new at developing and i got 2 errors i can't seem to find an answer on google. here is my code and the errors are
Cannot find 'self' in scope
Cannot find 'present' in scope
//
// ViewController.swift
// Diabell
//
// Created by Richard Klug on 14/04/2021.
//
import UIKit
import MessageUI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func emailbButtonTapped( sender: Any) {
showMailComposer()
}
}
func showMailComposer() {
guard MFMailComposeViewController.canSendMail() else{
return
}
let composer = MFMailComposeViewController()
composer.mailComposeDelegate = self
composer.setToRecipients(["richard.klug@diabell.se"])
composer.setSubject("Diabell App Help")
composer.setMessageBody("Fyll i vad du behöver hjälp med", isHTML: false)
present(composer, animated: true)
}
extension ViewController: MFMailComposeViewControllerDelegate {
func mailComposeController( controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
if let _ = error {
controller.dismiss(animated: true)
return
}
switch result {
case .cancelled:
print ("Cancelled")
case .failed:
print ("Failed to send")
case .saved:
print ("Saved")
case .sent:
print ("Email Sent")
}
controller.dismiss(animated: true)
}
}
Post marked as unsolved
98
Views
Hi, I have started learning Swift recently and due to system specifications, I am learning how to build apps for iOS 12.
I have written a code to update UI based on user's click.
Note : This function is called in the IBAction Function
//Here i is a global variable
scoreLabel.text = "Score : \(score)"
progressLabel.text = "Question: \(questionNumber+1) / 13"
progressBar.frame.size.width = (CGFloat(view.frame.size.width) / 13) * CGFloat(i)
print("i: \(i)")
i = i + 1
//CGFloat(allQuestion.list.count) * CGFloat(questionNumber + 1)
print(progressBar.frame.size.width)
}
But the progress bar frame is not getting updated. I checked and the value is getting updated but when I check on simulator, the progress bar is not updating, rest all are fine.
Kindly help me out to solve this issue
Post marked as unsolved
22
Views
Hi everyone
I am developing app on SwiftUI and I faced a very strange issue which I guess some of you might have already faced.
So I have my View with custom Navigation system, and it works fine on every single iOS starting 13.2 but if I run my app on simulator 13.0 or 13.1, it shows blank screen everywhere I use navigation.
What is even more interesting, if I add NavigationView {} to the top of the content of my view, the content starts to show but with the blank space at the top (I literally use two navigations on one screen)
My question is have anyone already faced similar problems? Is there any solution or this is just a bug of simulator or something? I cannot test on a real device since all of them are running iOS 14 and later and I cannot find an iOS 13 device anywhere.
Please help me someone
Post marked as unsolved
15
Views
At this moment I need to make an APP that can upgrade MFI devices. I can use EAaccessoy to communicate between devices and send and receive devices. How should I upgrade it? I try to use Mcumgr's Framework, but because the library is for BLE devices The library is of no use to me?
Is there a library that can be used to upgrade the MFI device for reference? I use the IAP2 communication protocol.