Hi everyone,
I've implemented a UIPasteControl in my iOS app using the following code:
func displayPasteControl() {
if #available(iOS 16.0, *) {
let pasteControlConfig = UIPasteControl.Configuration()
let newPasteControlButton = UIPasteControl(configuration: pasteControlConfig)
self.inputContainerView.addSubview(newPasteControlButton)
newPasteControlButton.isEnabled = true
// Set constraints for this button
newPasteControlButton.translatesAutoresizingMaskIntoConstraints = false
newPasteControlButton.topAnchor.constraint(equalTo: self.originalPasteView.topAnchor, constant: 0).isActive = true
newPasteControlButton.centerXAnchor.constraint(equalTo: self.inputContainerView.centerXAnchor).isActive = true
newPasteControlButton.widthAnchor.constraint(equalTo: self.originalPasteView.widthAnchor, multiplier: 0.5).isActive = true
newPasteControlButton.bottomAnchor.constraint(equalTo: self.originalPasteView.bottomAnchor, constant: 0).isActive = true
newPasteControlButton.target = self.inputTextView
}
}
I call this function in viewWillAppear:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
displayPasteControl()
}
Sometimes, I've noticed that the UIPasteControl button appears in a disabled state visually, but when I press it, the content from the clipboard is still pasted. I checked the state of UIPasteControl and it indicates that it is in an enabled state.
For context, the UIPasteControl target is set to a UITextView (self.inputTextView).
Has anyone experienced this issue or have any idea why this might be happening? Any help would be appreciated!
Thank you!
Swift
RSS for tagSwift is a powerful and intuitive programming language for Apple platforms and beyond.
Posts under Swift tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Every time I dismiss ImmersiveSpace with progressive ImmersionStyle and open another one I get about 30-40% of immersion level. Can immersion be set to 100% in progressive by default?
The following videos from WWDC24 say that we can use cloud storage for our SwiftData stores. Video references below:
What's new in SwiftData
Create a custom data store with SwiftData
When watching the videos it shows examples of how we can read and write to a JSON file as a store, rather than using the built in store that comes with SwiftData.
But there are mentions that we can use cloud storage like a backend i.e. a database hosted on a server. The only thing that I'm struggling to figure out and it would be great if we had code samples for this is how to achieve using cloud storage as a store since looking at the current implementations of:
DataStoreConfiguration
DataStore
The required functions we need to implement look synchronous rather than asynchronous so how would or could we handle fetching asynchronous data from cloud storage. So how would we handle this?
Also it would be great if someone could clarify how or if there is a way to send notifications for changes to your store between different devices similar to CloudKit?
Are there there any plans to provide more documentation & sample code for the questions I've asked above?
Feedback FB13857743
Hey,
the TipViewStyle protocol seems to still be nonisolated, which makes using it in the Swift 6 language mode impossible, I believe (at least without using something like MainActor.assumeIsolated):
@available(macOS 14.0, iOS 17.0, tvOS 17.0, visionOS 1.0, watchOS 10.0, *)
public protocol TipViewStyle {
// ...
}
I cannot use any views inside the makeBody method.
Other style protocols, like ButtonStyle are correctly isolated to the main actor:
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
@MainActor @preconcurrency public protocol ButtonStyle {
// ...
}
Is this just an oversight or am I missing something and this is actually intentional?
Thanks!
I am trying to implement both ContextMenu and Drag&Drop in UITableView like Apple home screen or Photo app, but the contextual menu prevent dragging in iOS.
I didn’t achieve this. apple provide any separate API for this?
Hi team,
we have any separate API for dragging with contextual menu?. kindly update it.
I'm working on an app that uses HomeKit-enabled accessories such as wall plugs to control a photographic enlarger in a darkroom. This requires precise timing when toggling the power state of the plug. For example, the timer in my app might be set to 5 seconds, so I turn on the plug using writeValue() on the plugs power state characteristic, wait 5 seconds, then turn it off again.
I want to be able to measure if the plug actually responded to the command and if there was any delay in the plug actually turning on/off so I can display a warning to the user if network latency resulted in the plug being on for longer than the set time.
Does writeValue() (in my case, the async/await version) only return when the plug has been turned on, or does it return as soon as the command has been sent, regardless of if it has been received/acted on? Is there a way I can (a) quickly verify that the plug has been turned on/off, and (b) measure how long it took for the plug to act on the request, that is, the time elapsed between when writeValue() is called and when the plug actually updates to the corresponding value?
Before anyone rants and raves about checking documentation - I have spent the last 4 hours trying to solve this issue on my own before asking for help. Coding in Swift is VERY new for me and I'm banging my head against the wall trying to teach myself. I am very humbly asking for help. If you refer me to documentation, that's fine but I need examples or it's going to go right over my head. Teaching myself is hard, please don't make it more difficult.
I have ONE swift file with everything in it.
import Foundation
import Cocoa
import Observation
class GlobalString: ObservableObject {
@Published var apiKey = ""
@Published var link = ""
}
struct ContentView: View {
@EnvironmentObject var globalString: GlobalString
var body: some View {
Form {
Section(header: Text("WallTaker for macOS").font(.title)) {
TextField(
"Link ID:",
text: $globalString.link
)
.disableAutocorrection(true)
TextField(
"API Key:",
text: $globalString.apiKey
)
.disableAutocorrection(true)
Button("Take My Wallpaper!") {
}
}
.padding()
}
.task {
await Wallpaper().fetchLink()
}
}
}
@main
struct WallTaker_for_macOSApp: App {
@AppStorage("showMenuBarExtra") private var showMenuBarExtra = true
@EnvironmentObject var globalString: GlobalString
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(GlobalString())
}
// MenuBarExtra("WallTaker for macOS", systemImage: "WarrenHead.png", isInserted: $showMenuBarExtra) {
// Button("Refresh") {
//// currentNumber = "1"
// }
// Button("Love It!") {
//// currentNumber = "2"
// }
// Button("Hate It!") {
//// currentNumber = "3"
// }
// Button("EXPLOSION!") {
// // currentNumber = "3"
// }
////
// }
}
}
class Wallpaper {
var url: URL? = nil
var lastPostUrl: URL? = nil
let mainMonitor: NSScreen
init() {
mainMonitor = NSScreen.main!
}
struct LinkResponse: Codable {
var post_url: String?
var set_by: String?
var updated_at: String
}
struct Link {
var postUrl: URL?
var setBy: String
var updatedAt: Date
}
func parseIsoDate(timestamp: String) -> Date? {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter.date(from: timestamp)
}
func fetchLink() async {
do {
url = URL(string: GlobalString().link)
let (data, _) = try await URLSession.shared.data(from: url!)
let decoder = JSONDecoder()
let linkResponse = try decoder.decode(LinkResponse.self, from: data)
let postUrl: URL? = linkResponse.post_url != nil ? URL(string: linkResponse.post_url!) : nil
let date = parseIsoDate(timestamp: linkResponse.updated_at)
let link = Link(
postUrl: postUrl,
setBy: linkResponse.set_by ?? "anon",
updatedAt: date ?? Date()
)
try update(link: link)
} catch {
}
}
func update(link: Link) throws {
guard let newPostUrl = link.postUrl else {
return
}
if (newPostUrl != lastPostUrl) {
lastPostUrl = newPostUrl
let tempFilePath = try getTempFilePath()
try downloadImageTo(sourceURL: newPostUrl, destinationURL: tempFilePath)
try applyWallpaper(url: tempFilePath)
} else {
}
}
private func applyWallpaper(url: URL) throws {
try NSWorkspace.shared.setDesktopImageURL(url, for: mainMonitor, options: [:])
}
private func getTempFilePath() throws -> URL {
let directory = NSTemporaryDirectory()
let fileName = NSUUID().uuidString
let fullURL = NSURL.fileURL(withPathComponents: [directory, fileName])!
return fullURL
}
private func downloadImageTo(sourceURL: URL, destinationURL: URL) throws {
let data = try Data(contentsOf: sourceURL)
try data.write(to: destinationURL)
}
}
The 'fetchLink' function is where things explode, specifically when setting the URL. I do not know what I'm doing wrong.
I have a public swift function with the below declaration :
public func InternalMain (_ pNumOfArgs : Int32, _ pCmdlineArgs : UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>) -> Int32 {..}
I need this function as public because I need to invoke in from a different library. But the above declaration produces an error in my generated swift header i.e '-swift.h' file because 'UnsafeMutablePointer<UnsafeMutablePointer?>' type cannot be represented in the swift generated header.
Can someone help how do I get past this. This is a class independent function and I tried using the '@nonobj' to prevent this from getting in the generated header but it still gives an error.
I have created an MKLocalSearch request as follows:
let reqVenue = MKLocalSearch.Request()
reqVenue.naturalLanguageQuery = "Music Venue"
reqVenue.resultTypes = .pointOfInterest
reqVenue.region = .init(center: mockCoord, latitudinalMeters: 150, longitudinalMeters: 150)
I have made sure mockCoord is the exact location coordinate of the example music venue I want to get back in the response. I have noticed that all Music Venues I can find on Apple Maps do not come back as results in MKLocalSearch. I would love an explanation as to why and what I can do to make them appear in MKLocalSearch results please!
best,
nick
In truth, I do not fully understand JSON Files and I am new to Swift. I am trying to be a bit too clever and build my menu from a JSON file.
[
{
"description": "Readings Entry",
"target": "ReadingsEntry",
"icon": "barometer",
},
{
"description": "Readings Entry",
"target": "ReadingsView()",
"icon": "tablecells.badge.ellipsis",
},
{
"description": "Food Diary",
"target": "FoodDiary()",
"icon": "fork.knife.circle",
},
{
"description": "Readings Entry",
"target": "Settings()",
"icon": "gearshape",
}
]
Because I don't know any better I have stored the destination view (target) as a String in the "struct" that I have constructed to import the JSON data.
import SwiftUI
struct dcMenu: Codable, Identifiable {
enum CodingKeys: CodingKey {
case description
case target
case icon
}
var id = UUID()
var description: String
var target: String
var icon: String
}
class ReadData: ObservableObject {
@Published var lineText = [dcMenu]()
init(){
loadData()
}
func loadData() {
guard let url = Bundle.main.url(forResource: "menu", withExtension: "json")
else {
print("Json file not found")
return
}
let data = try? Data(contentsOf: url)
let lineText = try? JSONDecoder().decode([dcMenu].self, from: data!)
self.lineText = lineText!
}
}
But the issue this leaves me with is when I come to construct the actual menu, How do I use the string "target" as the "destination" of the navigation link?
struct ContentView: View {
@ObservedObject var menuLines = ReadData()
var body: some View {
NavigationSplitView {
.
.
.
List(menuLines.lineText) { lines in
NavigationLink(destination: lines.target){
Image(systemName: lines.icon)
Text(lines.description)
}
}
.
.
.
.navigationSplitViewColumnWidth(min: 75, ideal: 100)
} detail: {
.
.
.
}
.navigationTitle("Diabetes Control")
}
}
Hello, I'm using the generator to create a client from this API:
https://github.com/griptape-ai/griptape-cloud-control-plane/blob/main/models/Griptape.openapi.json
Everything seems fine until I go to call a method. I get an error on a DateTime format mismatch in the response.
Client error - cause description: 'Unknown', underlying error: DecodingError: dataCorrupted - at : Expected date string to be ISO8601-formatted. (underlying error: <nil>),
Is there a decoder option or something I can attach to the generated client code to adjust for this?
I am trying to encode an AttributedString to JSON and then decode it back to an AttributedString. But when the AttributedString both (1) contains emoji, and (2) has any attributes assigned, the decoding seems to fail, producing a truncated AttributedString. By dump-ing the decoded value, I can see that the full string is still in there (in the guts property) but it is missing in normal uses of the AttributedString.
Below is an example that reproduces the problem.
import Foundation
// An arbitrary AttributedString with emoji
var attrString = AttributedString("12345💕☺️💕☺️💕☺️12345")
// Set an attribute (doesn't seem to matter which one)
attrString.imageURL = URL(string: "http://www.dummy.com/dummy.jpg")!
// Encode the AttributedString
var encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try! encoder.encode(attrString)
// Print the encoded JSON
print("encoded JSON for AttributedString:")
print(String(data: data, encoding: .utf8)!)
// Output from above omitted, but it looks correct with the full string represented
// Decode the AttributedString and print it
let decoder = JSONDecoder()
let decodedAttrString = try! decoder.decode(AttributedString.self, from: data)
print("decoded AttributedString:")
print(decodedAttrString)
// Output from above is a truncated AttributedString:
//
// 12345💕☺️ {
// NSImageURL = http://www.dummy.com/dummy.jpg
// }
print("dump of AttributedString:")
dump(decodedAttrString)
// Interestingly, `dump` shows that the full string is still in there:
//
// ▿ 12345💕☺️ {
// NSImageURL = http://www.dummy.com/dummy.jpg
// }
// ▿ _guts: Foundation.AttributedString.Guts #0
// - string: "12345💕☺️💕☺️💕☺️12345"
// ▿ runs: 1 element
// ...
//
Since I start to wrote UITest, this keep happened with no waring, following image
is the log, sensitive info has been replaced.
However, once I run app, then run test again, UITest just work out, it seems like a wired but, and the method just a working around bug to me,
What have I done wrong? I am trying to "List" a set of string values from an array, I spent all day trying to get it to work. What have I done wrong?
import SwiftUI
struct ContentView: View {
@State private var menuItems = ["Settings", "Readings Entry", "Food Diary"]
@State private var targets = ["Settings()", "ReadingsEntry()", "FoodDiary()"]
var body: some View {
NavigationStack {
List {
ForEach(menuItems) { menuLine in
print(menuLine)
}
}.navigationTitle("Menu")
}
}
}
The latest set of Error messages are:
Against the ForEach Line : Cannot convert value of type '[String]' to expected argument type 'Range'
Against the print line3: Type '()' cannot conform to 'View'
Hello there.
I'm having trouble with notarization in Xcode.
I'm developing a Swift Mac app with Xcode 14, but even when I enable Hardened Runtime and perform notarization, it displays the message "Hardened Runtime is not enabled" and I can't proceed.
The steps for notarization are [Window] -> [Organizer] -> [Distribute App] -> [Developer ID] [Next] -> [Upload].
Could you please tell me what I should check, or any other information?
I've attached screenshots.
Thank you.
Have a bug I'm trying to resolve on an app review through the store.
The basic flow is this:
User presses a button and enters a fully immersive space
While in the the fully immersive space, user presses the digital crown button to exit fully immersive mode and return to shared space (Note: this is not rotating the digital crown to control immersion level)
At this point I need an event or onchange (or similar) to know when a user is in immersive mode so I can reset a flag I've been manually setting to track whether or not the user is currently viewing an immersive space.
I have an onchange watching the scenePhase changes and printing to console the old/new values however this is never triggered.
Seems like it might be an edge case but curious if there's another way to detect whether or not a user is in an immersive scene.
I'm building a macOS target for my App (which also has some Obj-C code).
Building and running the app is fine but when I archive the app in XCode, the process / build fails with the following error
Type 'BOOL' (aka ;Int32') cannot be used as a boolean;test for '!=0' instead
It happens in a couple of places, one of the places being
private func getRootDirectory(createIfNotExists: Bool = true) throws -> URL {
return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
}
where it complains that create: true is not acceptable and throws the above error.
If I comment out this line, the archive works successfully.
When i Cmd + click the definition of Filemanager.default.url , i get this
@available(macOS 10.6, *)
open func url(for directory: FileManager.SearchPathDirectory, in domain: FileManager.SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: BOOL) throws -> URL
This looks fishy since it it says create shouldCreate: BOOL whereas the documentation says it should be just Bool
func url(
for directory: FileManager.SearchPathDirectory,
in domain: FileManager.SearchPathDomainMask,
appropriateFor url: URL?,
create shouldCreate: Bool
) throws -> URL
My minimum deployment target is macOS 13.0
I'm quite stumped at this error - which happens only while archiving. Does anybody know why?
I'm trying to capture audio samples from the selected output device on macOS using ScreenCaptureKit?
Thank you
I am trying to create demo for spatial meeting using persona also refer apple videos, But not getting clear idea about it.
Any one could you please guide me step by step process or any code are appreciated for learning.