Dive into the world of programming languages used for app development.

All subtopics

Post

Replies

Boosts

Views

Activity

Swift from the commandline
I always find it instructive to start from the commandline. When I subsequently migrate to IDE, my feet are on the ground.I've been trying with a basic "hello world" style Swift snippet: the challenge is to draw a window on the screen without using Xcode.Now Swift has a compiler and an interpreter. So the challenge bifurcates -- to get it running on each.Could someone provide a set of instructions for each, together with an explanation of what's going on?π
6
1
9.6k
Jun ’15
Best workaround for the lack of generic protocols
Let's say I have a protocol "ValueProvider", which is just something that provides a value:protocol ValueProvider { typealias ValueType func valueInContext(context: ValueProviderContext) -> ValueType }I have various structs that implement this protocol, such as:struct Constant<T>: ValueProvider { var value: T init(value: T) { self.value = value } func value(context: ValueProviderContext) -> T { return value } }and many other such (generic) structs.I have another struct, Thing, that has properties which are value provides of particular type. Ideally, I would like to express it like this:struct Thing { var position: ValueProvider<CGPoint> var name: ValueProvider<String> ... }Unfortunately I cannot do this, because ValueProvider is a protocol (which cannot be generic in current version of Swift), and ValueProvider<String> is illegal as a property type.It looks to me I basically have two options:(1) Make a new generic ThingProperty<T> enum, use that as the type of the "position" and "name" properties. The enum will have a value provider as its associated value. I don't like this solution because it forces me to change my model only because the type system cannot express what I want, although the runtime shouldn't have any problem with what I want. It feels like changing my model just to make the typechecker happy, which is absurd.(2) Instead of "ValueProvider<CGPoint>", I can just use "ValueProvider" as the type of the position (and name) properties. This works and allows me to keep the model simple, but I loose the benefits of static typing to a large degree - the system doesn't know that the "position" and "model" properties can only hold CGPoint and String value providers, respectively. As a consequence, when I call valueInContext method on those properties, type checker wouldn't know the correct type of the return value.What's the "correct" approach to take here? Am I missing something?
25
0
19k
Jun ’15
URL from string with spaces in it
How do I construct a URL from a string with spaces in it?For example: http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quote where symbol in ("AAPL")let text = "http:// + "query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quote where symbol in ("AAPL")&format=json&env=http://datatables.org/alltables.env" let url = NSURL(String: text)returns url = nilIn related, what must I do re the Apple Transport policy to make this secure?Just making it https (rather than http) doesn't seem to be sufficient."
8
1
16k
Oct ’15
Custom Filter Code Help
HiHope all is well?I'm trying to make my own app and have run into my first issue hahaI'm a cinematographer that makes LUTS for cinematographers for many different camera platforms. I also make them for iPhone users so I want to create my own app so they can use them in the phone/app rather then on a computer.Long story short, LUTS are kinda like filters, Instagram filters etc.....But instead of applying a typical Apple filter like CISepiaTone etcWhen the users applies the filters from the app, I need the filter to be applied from a png file not a Apple filterI know it's possible but I can't seem to find a code that works.So basically, users import a picture/video from their photo library, they then apply the filter and save it to their phone.I just need it to apply my own filters from png files not a CI FilterThis is my code so far:import UIKitclass ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() / } func importImage(_ sender: Any) { let image = UIImagePickerController() image.delegate = self image.sourceType = UIImagePickerControllerSourceType.photoLibrary image.allowsEditing = true self.present(image, animated: true) { / } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { imageView.image = image}else{ /}self.dismiss(animated: true, completion: nil)} func filterAction(_ sender: Any) { guard let image = self.imageView.image?.cgImage else { return } let openGLContext = EAGLContext(api: .openGLES3) let context = CIContext(eaglContext: openGLContext!) let ciImage = CIImage(cgImage: image) let filter = CIFilter(name: "CISepiaTone") filter?.setValue(ciImage, forKey: kCIInputImageKey) filter?.setValue(1, forKey: kCIInputIntensityKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage { self.imageView?.image = UIImage(cgImage: context.createCGImage(output, from: output.extent)!) } / } }so the last filter action I need to change from a CI filter to filter with my png fileAny ideas? im using Xcode 8.2.1 with Swift Please email me here danieljohnpeters@yahoo.comMany thanks in advance
1
0
558
Jan ’17
How much does it cost to develop an app like Airbnb?
I’d like to develop an online marketplace and service provider iOS app similar to the Airbnb app for my startup company. I need standard functions like email registration, user profile, listings etc. And special functions like: location tracking, map, booking system, embedded messenger for the host and customers, internet surveillance camera and rating system, payment system.I have two questions:-How much does it cost?-Is it possible to develop it by myself and how long?(no programming background)
23
0
8.1k
Apr ’17
How to present and dismiss intermediate view controllers?
Hello, everyone!I'm trying to figure out the best way to correctly present and dismiss view controllers in Swift. I am trying to do this without the Storyboard at all, since I like coding that way. I would like to present a scenario, that I'm in. I have three view controllers; VC1, VC2 and VC3, my root view controller would be VC1. If i use thispresent(VC2(), animated: true completion: nil)in VC1, then that takes me to VC2. Then I call this method again, but where I present VC3. My questions then is, how do I dismiss both VC2 and VC3 at the same time, bringing me back to VC1?I have tried many ways to do this, but I always end up having to briefly showing the "middle" view controller. Is there any way to avoid this?
10
0
1.0.0k
Sep ’17
Best practice to force upgrade app
Hi, I would like to implement force update app to support new API changes. I got many solutions, but need adivce to follow best practices like where to extaclty check for the app version(Make API to get app version to compare). Also, would like to stop checking version(atleast for somedays) once the user update app to avoid making version check API call again.
10
5
68k
Aug ’18
invalid mode 'kCFRunLoopCommonModes'
invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debugI get this warning when I tap either of the switches shown below. I've tried capturing the switch state in a var and using that to trigger the do/catch statement but no joy. I've even tried pulling the do/catch into separate functions and I still get the warning. Has anybody else run into this and how did you fix it?@IBAction func greetingFormat_Tapped(_ sender: UISwitch) { let theQuery = theTable_Settings.filter(settingID == 1) if sender.isOn { do { if try Database.shared.databaseConnection!.run(theQuery.update(greeting_Format <- "true")) > 0 { greetingFormatLabel_Outlet.text = NSLocalizedString("HelloMrSmith_String", comment: "") } else { print("greeting format true not found") } } catch { print("greeting format true update failed! Error: \(error)") } } else { do { if try Database.shared.databaseConnection!.run(theQuery.update(greeting_Format <- "false")) > 0 { greetingFormatLabel_Outlet.text = NSLocalizedString("HiJoe_String", comment: "") } else { print("greeting format false not found") } } catch { print("greeting format false update failed! Error: \(error)") } } }@IBAction func nonrefundableSwitch_Tapped(_ sender: UISwitch) { let theQuery = theTable_Settings.filter(settingID == 1) var itsOn: String = "" if sender.isOn { itsOn = "true" } else { itsOn = "false" } if itsOn == "true" { do { if try Database.shared.databaseConnection!.run(theQuery.update(nonRefundable_Bool <- "true")) > 0 { depositDueLabel_Outlet.text = NSLocalizedString("nonRefunddepositisdue_String", comment: "") } else { print("nonRefundable true not found") } } catch { print("nonRefundable true update failed! Error: \(error)") } } else { do { if try Database.shared.databaseConnection!.run(theQuery.update(nonRefundable_Bool <- "false")) > 0 { depositDueLabel_Outlet.text = NSLocalizedString("depositisdue_String", comment: "") } else { print("nonRefundable false not found") } } catch { print("nonRefundable false update failed! Error: \(error)") } } }
33
2
22k
Apr ’20
Variable WidgetBundle Configurations possible?
I am trying to implement a variable configuration for my WidgetBundle. For example, I would like to have a widget only available for certain customers. The general idea would be some like this like: @main struct Widgets: WidgetBundle {     @WidgetBundleBuilder     var body: some Widget { if Membership.active? { WidgetA() WidgetB() WidgetPremium()     } else { WidgetA() WidgetB() } } } I realize that this particular syntax is invalid, but I've tried all manner of Function builder syntaxes I could think of to make something like this work but haven't been able to get any to work for widgets. In SwiftUI we have the conditional function builders, but I can't quite discover if they don't exist here or I'm just missing them. Is this type of configurability possible? Thank you!
4
1
2.3k
Jul ’20
Obtaining CPU usage by process
Hi there, I'm working on an app that contains a mini system monitoring utility. I would like to list the top CPU-using processes. As Quinn “The Eskimo!” has repeatedly cautioned, relying on private frameworks is just begging for maintenance effort in the future. Ideally, I want to go through public headers/frameworks. I've gone to great lengths to try to find this information myself, and at this point I'm just struggling. I detail my research below. Any pointers in the right direction would be much appreciated! Attempts Libproc First I looked at libproc. Using proc_pidinfo with PROC_PIDTHREADINFO, I'm able to get each thread of an app, with its associated CPU usage percentage. Summing these, I could get the total for an app. Unfortunately, this has two downsides: Listing a table of processes now takes O(proces_count) rather than just O(process_count), and causes way more syscalls to be made It doesn't work for processes owned by other users. Perhaps running as root could alleviate that, but that would involve making a priviliedged helper akin to the existing sysmond that Activity Monitor.app uses. I'm a little scared of that, because I don't want to put my users at risk. Sysctl Using the keys [CTL_KERN, KERN_PROC, KERN_PROC_PID, someProcessID], I'm able to get a kinfo_proc - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/sysctl.h#L750-L776 instance. Accessing its .kp_proc - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/proc.h#L96-L150.p_pctcpu - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/proc.h#L123 looked really promising, but that value is always zero. Digging deeper, I found the kernel code that fills this struct in (fill_user64_externproc - https://github.com/apple-opensource/xnu/blob/c76cff20e09b8d61688d1c3dfb8cc855cccb93ad/bsd/kern/kern_sysctl.c#L1121-L1168). The assignment of p_pctcpu - https://github.com/apple-opensource/xnu/blob/c76cff20e09b8d61688d1c3dfb8cc855cccb93ad/bsd/kern/kern_sysctl.c#L1149 is in a conditional region, relying on the _PROC_HAS_SCHEDINFO_ flag. Disassembling the kernel on my mac, I could confirm that the assignment of that field never happens (thus _PROC_HAS_SCHEDINFO_ wasn't set during compilation, and the value will always stay zero) Reverse engineering Activity Monitor.app Activity Monitor.app makes proc_info and sysctl system calls, but from looking at the disassembly, it doesn't look like that's where its CPU figures come from. From what I can tell, it's using private functions from /usr/lib/libsysmon.dylib. That's a user library which wraps an XPC connection to sysmond (/usr/libexec/sysmond), allowing you to create requests (sysmon_request_create), add specific attributes you want to retrieve (sysmon_request_add_attribute), and then functions to query that data out (sysmon_row_get_value). Getting the data "striaght from the horses mouth" like this sounds ideal. But unfortunately, the only documentation/usage I can find of sysmond is from bug databases demonstrating a privilege escalation vulnerability lol. There are some partial reverse engineered header files floating around, but they're incomplete, and have the usual fragility/upkeep issues associated with using private APIs. On one hand, I don't want to depend on a private API, because that takes a lot of time to reverse engineer, keep up with changes, etc. On the other, making my own similar privileged helper would be duplicating effort, and expose a bigger attack surface. Needless to say, I have no confidence in being able to make a safer privileged helper than Apple's engineers lol Reverse engineering iStat Menus Looks like they're using proc_pid_rusage - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/libsyscall/wrappers/libproc/libproc.h#L103-L108 . However, I don't know how to convert the cpu_*_time fields of the resulting struct rusage_info_v4 - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/resource.h#L306-L343 to compute a "simple" percentage. Even if I came up with some formula that produces plausible looking results, I have no real guarantee it's correct or equivalent to what Activity Monitor shows.
5
1
4.7k
Jul ’20
Error creating LLDB target at path - Xcode 12
I'm using Xcode 12 beta 3. When running my Apple Watch's target on WatchOS 7, I get this error: Warning: Error creating LLDB target at path '/Users/evan/Library/Developer/Xcode/DerivedData/audigo-cneguthkmmoulfgcprsazbryrlrl/Build/Products/Debug-watchsimulator/AudigoWatchApplication.app'- using an empty LLDB target which can cause slow memory reads from remote devices. I know this error use to be when running 32 bit frameworks on 64 bit devices, but I'm not doing that. Is this a bug? Or is there a setting I don't know of that needs to be updated?
20
2
22k
Jul ’20
Is there a way to access Managed Preferences through UserDefaults in Swift?
I’d like to access the values in plist files in /Library/ManagedPreferences. I tried UserDefaults.standard.object(forKey: "com.custom.app.domain") but that did not work My goal is to deploy settings that are set in an MDM and read those settings in my Swift macOS app. I’m new to macOS development and have been banging my head against the internet trying to figure out how to do this. Would really appreciate any help, thank you!
3
1
595
Aug ’20
Why does Combine assign crash when writing to an optional property?
This code crashes ("Unexpectedly found nil while unwrapping an Optional value") import Combine class Receiver { &#9;&#9;var value: Int! &#9;&#9;var cancellables = Set<AnyCancellable>([]) &#9;&#9;init(_ p: AnyPublisher<Int,Never>) { &#9;&#9;&#9;&#9;p.assign(to: \.value, on: self).store(in: &cancellables) &#9;&#9;} } let receiver = Receiver(Just(5).eraseToAnyPublisher()) It does not crash if I use p.sink { self.value = $0 }.store(in: &cancellables) instead of the assign, and it does not crash if I do not use an optional for the value-property. To me this looks like a bug in Swift's constructor code, but maybe I am overlooking something?
1
1
1.2k
Aug ’20
Using UNNotificationServiceExtension with FCM not getting called
I don't know what could be wrong but my UNNotificationServiceExtension is never getting called by any push from FCM. I call the FCM from a Python3 script and so far it works (I get a push notification but always with the default text and not the modified one). firebaseHeaders = { "Content-Type":"application/json", "Authorization":"key=MYKEY" } firebaseBody = { "to":devicetoken, "priority":"high", "mutable-content":True, "apns-priority":5, "notification": { "titlelockey":"push.goalReachedTitle", "bodylockey":"push.goalReachedContentRemote", "bodylocargs":[str(entry['value']), entry['region']], "sound":"default", "badge":1 }, "data": { "values":data, "region":entry['region'], "value":entry['value'] } } firebaseResult = requests.post("https://fcm.googleapis.com/fcm/send", data=None, json=firebaseBody, headers=firebaseHeaders) My Extension is also pretty basic (for testing) and I already tried to remove it and add it again to my main app project without success. class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { bestAttemptContent.title = bestAttemptContent.title + " [TEST 123]" contentHandler(bestAttemptContent) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } } Anyone has a idea what I still can check, test or miss?
7
2
6.7k
Oct ’20
Invalid code signature problem with Xcode12
I'm practicing a swift 5 class, and have this issue: Could not launch “I AM RICH” Domain: IDEDebugSessionErrorDomain Code: 3 Failure Reason: The operation couldn’t be completed. Unable to launch com.superdie.I-AM-RICH because it has an invalid code signature, inadequate entitlements or its profile has not been explicitly trusted by the user. User Info: {     DVTRadarComponentKey = 855031;     RawLLDBErrorMessage = "The operation couldn\U2019t be completed. Unable to launch com.superdie.I-AM-RICH because it has an invalid code signature, inadequate entitlements or its profile has not been explicitly trusted by the user."; } I'm not sure what can I do, some help would be nice :)
24
5
51k
Nov ’20
Facing compilation errors if I call variable argument C++ API from swift lang
I have an API with variable arguments in C++ library. I am trying to call this API from swift language. But I am facing with compilation errors as below. If I tried by removing variable arguments from the API then it is compiling. Please help to fix the error with variable arguments. API is void netops_log(enum log_level loglevel, const char *format, ...); Compilation errors: FilterDataProvider.swift:73:9: error: 'netops_log' is unavailable: Variadic function is unavailable     netops_log(LOGLEVEL_DEBUG, "Starting the filter... from NE")     ^~~~~~~~~~~~ __ObjC.netops_log:2:13: note: 'netops_log' has been explicitly marked unavailable here public func netops_log(_ loglevel: log_level, _ format: UnsafePointer<Int8>!, _ varargs: Any...)       ^
2
0
1k
Nov ’20
GameCenter scores are not being posted to the leaderboard
Hello! Bare with me here, as there is a lot to explain! I am working on implementing a Game Center high score leaderboard into my game. I have looked around for examples of how to properly implement this code, but have come up short on finding much material. Therefore, I have tried implementing it myself based off information I found on apples documentation. Long story short, I am getting success printed when I update my score, but no scores are actually being posted (or at-least no scores are showing up on the Game Center leaderboard when opened). Before I show the code, one thing I have questioned is the fact that this game is still in development. In AppStoreConnect, the status of the leaderboard is "Not Live". Does this affect scores being posted? Onto the code. I have created a GameCenter class which handles getting the leaderboards and posting scores to a specific leaderboard. I will post the code in whole, and will discuss below what is happening. PLEASE VIEW ATTACHED TEXT TO SEE THE GAMECENTER CLASS! GameCenter class - https://developer.apple.com/forums/content/attachment/0dd6dca8-8131-44c8-b928-77b3578bd970 In a different GameScene, once the game is over, I request to post a new high score to Game Center with this line of code: GameCenter.shared.submitScore(id: GameCenterLeaderboards.HighScore.rawValue) Now onto the logic of my code. For the longest time I struggled to figure out how to submit a score. I figured out that in Xcode 12, they deprecated a lot of functions that previously worked for me. Not is seems that we have to load all leaderboards (or the ones we want). That is the purpose behind the leaderboards private variable in the Game Center class. On the start up of the app, I call authenticate player. Once this callback is reached, I call loadLeaderboards which will load the leaderboards for each string id in an enum that I have elsewhere. Each of these leaderboards will be created as a Leaderboard object, and saved in the private leaderboard array. This is so I have access to these leaderboards later when I want to submit a score. Once the game is over, I am calling submitScore with the leaderboard id I want to post to. Right now, I only have a high score, but in the future I may add a parameter to this with the value so it works for other leaderboards as well. Therefore, no value is passed in since I am pulling from local storage which holds the high score. submitScore will get the leaderboard from the private leaderboard array that has the same id as the one passed in. Once I get the correct leaderboard, I submit a score to that leaderboard. Once the callback is hit, I receive the output "Successfully submitted score to leaderboard". This looks promising, except for the fact that no score is actually posted. At startup, I am calling updatePlayerHighScore, which is not complete - but for the purpose of my point, retrieves the high score of the player from the leaderboard and is printing it out to the console. It is printing out (0), meaning that no score was posted. The last thing I have questions about is the context when submitting a score. According to the documentation, this seems to just be metadata that GameCenter does not care about, but rather something the developer can use. Therefore, I think I can cross this off as causing the problem. I believe I implemented this correctly, but for some reason, nothing is posting to the leaderboard. This was ALOT, but I wanted to make sure I got all my thoughts down. Any help on why this is NOT posting would be awesome! Thanks so much! Mark
6
1
3.4k
Dec ’20