Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Swift Documentation

Posts under Swift tag

2,234 results found
Sort by:
Post marked as solved
80 Views

Cannot convert value of type 'ChooseModel.Angle' to expected argument type 'Angle'

Hi, guys i got errors from my View like below : Is anyone who can help me to fix it? My model like:     var id = UUID()     var decision: String     var choices: [String]     var startAngle: Angle     var endAngle: Angle           @CodableColor var color: UIColor     struct Angle: Codable, Equatable {         var degrees: Double     } } My model view like: import SwiftUI class ChooseModelView: ObservableObject {     var midRadians: Double {         return Double.pi / 2.0 - (model.startAngle.degrees + model.endAngle.degrees) * .pi / 180 / 2.0     }     @Published var model = ChooseModel(decision: "What to eat tonight?", choices: ["Sushi", "Ramen", "Korean BBQ", "Chinese"], startAngle: ChooseModel.Angle(degrees: 0.0), endAngle: ChooseModel.Angle(degrees: 90.0), color: UIColor.green) My view like :                     let width: CGFloat = min(geometry.size.width, geometry.size.height)                     let height = width                     let center = CGPoint(x: width * 0.5, y: height * 0.5)                     path.move(to: center)                     path.addArc(                         center: center,                         radius: width * 0.5,                         startAngle: Angle(degrees: -90.0) + chooseMV.model.startAngle,                         endAngle: Angle(degrees: -90.0) + chooseMV.model.endAngle,                         clockwise: false)                     path.closeSubpath()                 }
Asked
by tankman.
Last updated
.
Post not yet marked as solved
72 Views

How can i save Angle and [Color] to UserDefaults ?

Hi everyone I'm new to SwiftUI and i try to make a simple app for random choices,So when you create a list choices that will turn to a Spin-WheelView.For now, I face two problems: First. I don't know how save Angle and Array to UserDefaults; Second: I don't know to connect choices view to spin-wheel view. Any helps i will appreciate it! thank you all. My model: import SwiftUI struct ChooseModel: Identifiable, Codable {     var id = UUID()     var decision: String     var choices: [String]     // i try to create Angle and [Colors] in my model,     // but they don't confirmed Codable, i don't know how to save them to User defaults. //    var startAngle: Angle //    var endAngle: Angle //    var colors: [Color] } Model View import SwiftUI class ChooseModelView: ObservableObject {     @Published var models = [ChooseModel]() {         didSet {             let encoder = JSONEncoder()             if let encoded = try? encoder.encode(models) {                 UserDefaults.standard.set(encoded, forKey: "models")             }         }     }     init() {         if let items = UserDefaults.standard.data(forKey: "models") {             let decoder = JSONDecoder()             if let decoded = try? decoder.decode([ChooseModel].self, from: items) {                 self.models = decoded                 return             }         }         self.models = []     } } My View: struct ChooseView: View {          @ObservedObject var chooseMV = ChooseModelView()     @State private var showingAddView = false          var body: some View {         NavigationView {             List {                 ForEach(chooseMV.models) { item in                     // Use NavigationLink to Each WheelView                     HStack {                         VStack(alignment: .leading) {                             Text(item.decision)                                 .font(.title3)                             HStack {                                 ForEach(item.choices, id: \.self) { choice in                                     Text("\(choice),")                                         .foregroundColor(Color.green)                                 }                             }                         }                         Spacer()                     }                                      }.onDelete(perform: remove)             }.navigationTitle("iChoose")                 .navigationBarItems(leading: EditButton(), trailing: Button(action: {                     self.showingAddView = true                 }, label: {                     Image(systemName: "plus")                 }))                 .sheet(isPresented: $showingAddView) {                     AddView(chooseMV: self.chooseMV)                 }         }     }     func remove(at offsets: IndexSet) {         chooseMV.models.remove(atOffsets: offsets)     } }
Asked
by tankman.
Last updated
.
Post not yet marked as solved
35 Views

Hiding Application Name over Toolbar?

I have a toolbar (NSToolbar) through a window controller (NSWindowController). I don't know which Xcode version does it, but the toolbar shows the name of the application next to the three window buttons. Can we hide the name? Old desktop applications that I developed several years ago don't show the name. I hope I can hide it. Muchos thankos.
Asked
by Tomato.
Last updated
.
Post not yet marked as solved
131 Views

Having trouble getting MusicKit Data into my SwiftUI view

Having trouble getting the data from MusicKit Searches back to my SwiftUI view. Normally I would use a @State variable for the decodable structure, but with MusicKit you dont need to decode anything and I can't figure out how to best get the data back to my view. I call the MusicKit function using .onAppear in my SwiftUI view func getAlbum() async throws -> MusicItemCollection<Album> {         var request = MusicCatalogResourceRequest<Album>(matching: \.id, equalTo: "1440881121")         let response = try await request.response()         print(response.debugDescription)         return response.items        printing debugDescription give these results: MusicCatalogResourceResponse<Album>(   items: [     Album(       id: "1440881121",       title: "Colors",       artistName: "Beck",       contentRating: "explicit",       copyright: Fonograf Records/Capitol Records; ℗ 2017 Fonograf Records, under exclusive license to UMG Recordings, Inc.,       genreNames: [         "Alternative",         "Music"       ],       isCompilation: false,       isComplete: true,       isDigitalMaster: true,       isSingle: false,       releaseDate: "2017-10-13",       trackCount: 11,       upc: "00602557176827" Hoe would you access all of the data in the debugDescription and use it in your SwiftUI view? I can only access the standard name and id. Is anyone using Codable to move the data through a data model? The documentation is not making sense to me even though I am usually ok using it. Also, should I be using `func getAlbum() async throws -> MusicCatalogResourceResponse {' instead of using MusicItemCollection? Thanks
Asked Last updated
.
Post marked as solved
1.8k Views

SwiftUI: which Markdown specification is supported?

Hi, thanks for adding markdown support in SwiftUI's Text with Xcode 13 and iOS 15! :) Even formatting like strikethrough works! Text("Hello ~~World~~") So which specification is supported?? This goes apparently beyond Commonmark (as strikethrough is not part of Commonmark specification). Is it GitHub Flavored Markdown or even a different spec?
Asked Last updated
.
Post not yet marked as solved
34k Views

Could not find module for target 'x86_64-apple-ios-simulator'; found: arm64, armv7-apple-ios, arm64-apple-ios, arm, armv7

I have build a custom framework and everything was working fine until the update of XCode 11. The new XCode 11 released and we now I am unable to run my Custom Framework into a project in Simulator. I always get this errorCould not find module 'CustomFrameworkName' for target 'x86_64-apple-ios-simulator'; found: arm64, armv7-apple-ios, arm64-apple-ios, arm, armv7Can someone please let me know how to fix this error. I have already tried adding the framework and tried running the same in a different project however I am not able to fix this. Any help would be appreciated. Thanks
Asked
by cbgcbfd.
Last updated
.
Post not yet marked as solved
2.6k Views

Can I use async/await under iOS15.0?

As I can see, all the async APIs in XCode13.0 beta requires a deployment target of iOS 15.0, is that means that I cannot use async/await under iOS 15.0?
Asked
by AllenChen.
Last updated
.
Post not yet marked as solved
39 Views

Snapshot listener duplicating data

Hello, I'm working on this chat app and I have a snapshot listener to keep track the number of messages (with a badge) each user receives. I'm using a table view with pagination. The problem I'm having that I can't figure out is when a user gets a message, the table view duplicates the user, increases the badge number every time a message is received. Then, if i open the messages and then i go back to the first VC, there is another duplicate of the user but with no badge number because it was cleared. Any help is greatly appreciated. VC override func viewDidAppear(_ animated: Bool) {     super.viewDidAppear(animated)           fetchMatches()   } func fetchMatches() {     fetchInfo { matches in       self.match = matches       self.matchedMessagesTV.reloadData()     }   }       func fetchInfo(completion: @escaping([Match]) -> Void) {     if lastDocument == nil {       let query = MATCH_INFO_COLLECTION.document(currentUID!)         .collection("info").order(by: MATCH_TIMESTAMP, descending: false)       query.limit(to: 10).addSnapshotListener { (snapshot, error) in                   guard let last = snapshot?.documents.last else { return }         guard let snap = snapshot else { return }         snap.documentChanges.forEach({ diff in                       let dictionary = diff.document.data()           let memberId = dictionary[DOCUMENT_ID] as? String ?? ""           let memberAge = dictionary[AGE] as? Int ?? 0           let memberName = dictionary[FIRST_NAME] as? String ?? ""           let memberImageUrl = dictionary[PROFILE_IMAGE_URL] as? String ?? ""           let memberCurrentCity = dictionary[CURRENT_CITY] as? String ?? ""           let matchTimestamp = dictionary[MATCH_TIMESTAMP] as? Double ?? 0.0           let messageCounter = dictionary[MESSAGE_COUNTER] as? Int ?? 0                       let matches = Match(memberId: memberId, memberAge: memberAge ,memberName: memberName, memberImageUrl: memberImageUrl, memberCurrentCity: memberCurrentCity, matchTimestamp: Date(timeIntervalSince1970: matchTimestamp), messageCounter: messageCounter)                       self.match.append(matches)           self.memberId = matches.memberId           self.lastDocument = last           completion(self.match)         })       }     } else {       matchedMessagesTV.tableFooterView = createSpinnerFooter()       let query = MATCH_INFO_COLLECTION.document(currentUID!)         .collection("info").order(by: MATCH_TIMESTAMP, descending: false)               DispatchQueue.main.async {         self.matchedMessagesTV.tableFooterView = nil       }       query.start(afterDocument: self.lastDocument!)         .limit(to: 10).addSnapshotListener { (snapshot, error) in                       guard let last = snapshot?.documents.last else { return }           guard let snap = snapshot else { return }           snap.documentChanges.forEach({ diff in                           let dictionary = diff.document.data()             let memberId = dictionary[DOCUMENT_ID] as? String ?? ""             let memberAge = dictionary[AGE] as? Int ?? 0             let memberName = dictionary[FIRST_NAME] as? String ?? ""             let memberImageUrl = dictionary[PROFILE_IMAGE_URL] as? String ?? ""             let memberCurrentCity = dictionary[CURRENT_CITY] as? String ?? ""             let matchTimestamp = dictionary[MATCH_TIMESTAMP] as? Double ?? 0.0             let messageCounter = dictionary[MESSAGE_COUNTER] as? Int ?? 0                           let matches = Match(memberId: memberId, memberAge: memberAge ,memberName: memberName, memberImageUrl: memberImageUrl, memberCurrentCity: memberCurrentCity, matchTimestamp: Date(timeIntervalSince1970: matchTimestamp), messageCounter: messageCounter)                           self.match.append(matches)             self.memberId = matches.memberId             self.lastDocument = last             completion(self.match)                         })         }}   } class Match {       var memberId: String   let memberAge: Int   let memberName: String   let memberImageUrl: String   let memberCurrentCity: String   let matchTimestamp: Date!   let messageCounter: Int       init(memberId: String, memberAge: Int, memberName: String, memberImageUrl: String, memberCurrentCity: String, matchTimestamp: Date, messageCounter: Int) {           self.memberId = memberId     self.memberAge = memberAge     self.memberName = memberName     self.memberImageUrl = memberImageUrl     self.memberCurrentCity = memberCurrentCity     self.matchTimestamp = matchTimestamp     self.messageCounter = messageCounter   } }
Asked
by eduardo73.
Last updated
.
Post not yet marked as solved
911 Views

How do I render a dynamically changing IOSurface to a CALayer or NSView?

I have a background process which is updating an IOSurface-backed CVPixelBuffer at 30fps. I want to render a preview of that pixel buffer in my window, scaled to the size of the NSView that's displaying it. I get a callback every time the pixelbuffer/IOSurface is updated. I've tried using a custom layer-backed NSView and setting the layer contents to the IOsurface -- which works when the view is created but it's never updated unless the window is resized or another window is in front of it. I've tried setting both my view and my layer SetNeedsDisplay(), I've tried changing the layerContentsRedrawPolicy to .onSetNeedsDisplay, I've tried making sure all my content and update code is happening on the UI thread, but I can't get it to dynamically update. Is there a way to bind my layer or view to the IOSurface once and then just have it reflect the updates as they happen, or, if not, at least mark the layer as dirty each frame when it changes? I've pored over the docs but I don't see a lot about the relationship between IOSurface and CALayer.contents, and when in the lifecycle to mark things dirty (especially when updates are happening outside the view). Here's example code: class VideoPreviewThumbnail: NSView, VideoFeedConsumer {   let testCard = TestCardHelper()       override var wantsUpdateLayer: Bool {     get { return true }   }   required init?(coder decoder: NSCoder) {     super.init(coder: decoder)     self.wantsLayer = true     self.layerContentsRedrawPolicy = .onSetNeedsDisplay      &#9;&#9;/* Scale the incoming data to the size of the view */      self.layer?.transform = CATransform3DMakeScale(       (self.layer?.contentsScale)! * self.frame.width / CGFloat(VideoSettings.width),       (self.layer?.contentsScale)! * self.frame.height / CGFloat(VideoSettings.height),       CGFloat(1)) &#9; /* Register us with the content provider */     VideoFeedBrowser.instance.registerConsumer(self)   }       deinit{     VideoFeedBrowser.instance.deregisterConsumer(self)   }       override func updateLayer() { &#9;&#9;/* ideally we woudln't need to do this */     updateLayer(pixelBuffer: VideoFeedBrowser.instance.renderer.pixelBuffer)   }    &#9;/* This gets called every time our pixelbuffer is updated (30fps) */   @objc   func updateFrame(pixelBuffer: CVPixelBuffer) {     updateLayer(pixelBuffer: pixelBuffer)   }       func updateLayer(pixelBuffer: CVPixelBuffer) {     guard let surface = CVPixelBufferGetIOSurface(pixelBuffer)?.takeUnretainedValue() else {      print("pixelbuffer isn't IOsurface backed! noooooo!")       return;     } &#9; /* these don't have any effect */ &#9; //&#9;&#9;self.layer?.setNeedsDisplay() //&#9;&#9;self.setNeedsDisplay(invalidRect: self.visibleRect)     self.layer?.contents = surface   } }
Asked
by awmcclain.
Last updated
.
Post not yet marked as solved
73 Views

Can you create and export information to a new Pages file from an app?

Is there an API or has anyone seen swift code in relation to having an app interact with Pages on iPhone/iPad? My app takes inputs from a user and then partially fills out a template. I would like to export that template to a new Pages document for the user to continue filling out the items that the app is not intended to do for them. I can do this to pdf, but then user can't modify (at least not without a full version of acrobat). Thanks.
Asked
by bwa.
Last updated
.
Post marked as solved
49 Views

Why is superview returning nil?

At the very bottom is my code where MainController initiates a subview called setController. The new subview is created when I click the button However, within setController's code I get back a nil when I try to the superview: override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("\(self.view.superview)" ?? "count->no parent") } I am assigning the second view as a subview, but obviously I am missing something. Have I misunderstood how UIView hierarchy works? class MainController: UIViewController { private lazy var setController = SetController() var invButton : MyButton! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black invButton = makeButton(vControl: self, btype: ButtType.inv, action: #selector(self.buttonAction(sender:))) invButton.frame.origin.x = self.view.frame.width * 0.1 invButton.frame.origin.y = self.view.frame.height * 0.1 invButton.setTitle("Settings", for: .normal) } override var prefersStatusBarHidden: Bool { return false } @objc func buttonAction(sender: UIButton!) { guard let theButton = sender as? MyButton else { return} UIView.transition(with: self.view, duration: 0.5, options: .transitionCurlDown, animations: { [self] in self.addChild(setController) self.view.addSubview(setController.view) setController.didMove(toParent: self) }, completion: nil) } }
Asked
by SergioDCQ.
Last updated
.
Post marked as solved
48 Views

XPC, Swift, ObjC, and arrays

I create a protocol that had, among other things: @objc func setList(_: [MyType], withReply: @escaping (Error?) -> Void) The daemon part is in Swift, while the calling part is in Objective-C. Because why not? (Actually, because the calling part has to deal with C++ code, so that's ObjC++; however, I wanted the stronger typing and runtime checking for the daemon part, so I wrote it in Swift.) The ObjC part uses NSArray<MyType*>. I set up an NSXPCConnection link, and create a (synchronous) proxy with the right protocol name. But when I try to do the XPC setList call, I get an error. I assume that's because it doesn't like the signature. (Surely this is logged somewhere? I couldn't find it, if so. 😩) But... if I have a signature of @objc func addItem(_: MyType, withReply: @escaping (Error?) -> Void), then it works. So I assume it's the array. (Oh, I've also tried it without the @objc; the protocol itself is defined as @objc.) I've tried changing to protocol signature to using NSArray, but same thing.
Asked
by kithrup.
Last updated
.
Post not yet marked as solved
50 Views

Access a raw value for pure enum without using associated type

I'm no enum expert but I enjoy playing around with them to make my project code easier to read and type safe. I've written a simple enum to track the selected type (a To-Many relationship property) for a CoreData entity and provide some formatting. enum Taxon {     case common(name: String)     case genus(name: String)     case species(name: String)     case subspecies(name: String)     case group(name: String)     case cultivar(name: String)     case variety(name: String)     case extended(name: String)     var typeName: String {         switch self {         case .common:       return "Common"         case .genus:        return "Genus"         case .species:      return "Species"         case .subspecies:   return "Subspecies"         case .group:        return "Group"         case .cultivar:     return "Cultivar"         case .variety:      return "Variety"         case .extended:     return "Taxonomny"         }     }     var formatted: String {         switch self {         case .common(let name):       return name.capitalized         case .genus(let name):        return name.capitalized         case .species(let name):      return name.lowercased()         case .subspecies(let name):   return String(format: "ssp. %@", name)         case .group(let name):        return String(format: "(%@ Group)", name)         case .cultivar(let name):     return String(format: "cv. %@", name)         case .variety(let name):      return String(format: "var. %@", name)         case .extended(let name):     return name.capitalized         }     } I could make the enum an associated type String but then I lose the ability to include arguments... Error message - Enum with raw type cannot have cases with arguments I can parse a Set of entity instance name as follows and this provides a perfectly formatted string, based on the var .formatted in the enum Taxon.     for name in setSorted {         let nameComp: String = name.component!         let nameType: String = name.type!.name!         var nameFormatted = String()         switch nameType {         case Taxon.common(name: nameType).typeName:     nameFormatted = Taxon.common(name: nameComp).formatted         case Taxon.genus(name: nameType).typeName:      nameFormatted = Taxon.genus(name: nameComp).formatted         case Taxon.species(name: nameType).typeName:    nameFormatted = Taxon.species(name: nameComp).formatted         case Taxon.subspecies(name: nameType).typeName: nameFormatted = Taxon.subspecies(name: nameComp).formatted         case Taxon.group(name: nameType).typeName:      nameFormatted = Taxon.group(name: nameComp).formatted         case Taxon.cultivar(name: nameType).typeName:   nameFormatted = Taxon.cultivar(name: nameComp).formatted         case Taxon.variety(name: nameType).typeName:    nameFormatted = Taxon.variety(name: nameComp).formatted         case Taxon.extended(name: nameType).typeName:   nameFormatted = Taxon.extended(name: nameComp).formatted         default: nameFormatted = "E R R O R : Taxon : switch"         }         stringNames.append(nameFormatted)         if setSorted.last != name {             stringNames.append("\(stringBetween)")         }      } However seems clunky to me. Surely there is more concise / better code? Elsewhere I have whittled this type of enumeration down to a one liner (to be clear, without the switch statement), but those one liners were based upon an enum with an associated type and also did not have (arguments). For example... let calendarComponent = EntityDate(rawValue: format)?.calendarComponent (where EntityDate is the enum of type NSNumber and format is the var of type NSNumber, inserted by a func and used to identify the appropriate calendarComponent.) So if I attempt a line code like this... let test = Taxon(rawValue: nameType) I am provided with a compiler message... 'Taxon' cannot be constructed because it has no accessible initializers I've attempted a few ways to prepare an initialiser by copying patterns I have for other enum but nothing has worked so far and I'd prefer to keep the enum pure (of its own type) so that I can include the argument (name: String). I've wasted a little too much time on this frankly unnecessary obsession, so I am wondering what I am missing?
Asked Last updated
.
Post not yet marked as solved
30 Views

Sending keyboard and mouse events to unfocused window.

Is there any way to send key/mouse events to unfocused windows? Currently my code looks like this: let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)       let key_d = CGEvent(keyboardEventSource: src, virtualKey: 0x12, keyDown: true) // key "1" press       let key_u = CGEvent(keyboardEventSource: src, virtualKey: 0x12, keyDown: false) // key "1" release       key_d?.postToPid( (Int32)(pid) )       key_u?.postToPid( (Int32)(pid) ) Unfortunately this is working just for application, which owns menu bar. I was trying different methods, but none of them is working. I would love to send those events directly to app by selecting specific window ID instead of pid, but anything working with not-focused apps will be good.
Asked
by Archont94.
Last updated
.