In swift if using custom dateFormat like "dd-mm-yyyy" and device follows japanese calendar now get dateForm dateFormatter , expected "30-05-Reiwa6". but dateFormatter return string is "30=05-0006"
Swift Student Challenge
RSS for tagAsk questions and connect with other challenge applicants.
Posts under Swift Student Challenge tag
44 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Hello everyone,I am a student who is working on my final project of my college.I do not get an official development account since I do not need to put my app on AppStore.
In my project,I need to use the camera of iOS device, and I know I need to add NSCameraUsageDesciption in Info.plist.However, as I add the description in my Info and build my project, it failed and says"Provisioning profile "iOS Team Provisioning Profile: " doesn't include the NSCameraUsageDescription and NSPhotoLibraryUsageDescription entitlements."
I also notice that in the Info.plist file, when I change the property type to entitlements,I just cannot find NSCameraUsageDescription when I add row.
What's the problem?Is this because I am not an official developer?
so my code is:
import UIKit
class CanvasView: UIView {
let originX: CGFloat = 150
let originY: CGFloat = 300
let squareSide: CGFloat = 100
var rubiksCubeDelegate: RubiksCubeDelegate? = nil
var fromCol: Int = -1
var fromRow: Int = -1
override func draw(_ rect: CGRect) {
drawFront()
drawTop()
drawRight()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let firstTouch = touches.first!
let fingerLocation = firstTouch.location(in: self)
fromCol = Int((fingerLocation.x - originX) / squareSide)
fromRow = Int((fingerLocation.y - originY) / squareSide)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let firstTouch = touches.first!
let fingerLocation = firstTouch.location(in: self)
let toCol: Int = Int((fingerLocation.x - originX) / squareSide)
let toRow: Int = Int((fingerLocation.y - originY) / squareSide)
print("V: from (\(fromCol), \(fromRow) to (\(toCol), \(toRow))")
rubiksCubeDelegate?.moveFinger(fromCol: fromCol, fromRow: fromRow, toCol: toCol, toRow: toRow)
}
func drawFront() {
drawsquare(col: 0, row: 0, color: .green)
drawsquare(col: 1, row: 0, color: .orange)
drawsquare(col: 2, row: 0, color: .blue)
drawsquare(col: 0, row: 1, color: .white)
drawsquare(col: 1, row: 1, color: .yellow)
drawsquare(col: 2, row: 1, color: .red)
drawsquare(col: 0, row: 2, color: .green)
drawsquare(col: 1, row: 2, color: .blue)
drawsquare(col: 2, row: 2, color: .orange)
}
func drawTop() {
drawTopParallelogram(col: 0, row: 0, color: .red)
drawTopParallelogram(col: 0, row: 1, color: .blue)
drawTopParallelogram(col: 0, row: 2, color: .green)
drawTopParallelogram(col: 1, row: 0, color: .yellow)
drawTopParallelogram(col: 1, row: 1, color: .red)
drawTopParallelogram(col: 1, row: 2, color: .white)
drawTopParallelogram(col: 2, row: 0, color: .blue)
drawTopParallelogram(col: 2, row: 1, color: .orange)
drawTopParallelogram(col: 2, row: 2, color: .green)
}
func drawRight() {
drawRightParallelogram(col: 0, row: 0, color: .orange)
drawRightParallelogram(col: 1, row: 0, color: .red)
drawRightParallelogram(col: 2, row: 0, color: .red)
drawRightParallelogram(col: 0, row: 1, color: .blue)
drawRightParallelogram(col: 1, row: 1, color: .orange)
drawRightParallelogram(col: 2, row: 1, color: .white)
drawRightParallelogram(col: 0, row: 2, color: .white)
drawRightParallelogram(col: 1, row: 2, color: .blue)
drawRightParallelogram(col: 2, row: 2, color: .green)
}
func drawRightParallelogram(col: Int, row: Int,color: CubeColor) {
colorOf(color: color).setFill()
let topLeftX: CGFloat = originX + 3 * squareSide + CGFloat(col) * squareSide/2
let topLeftY: CGFloat = originY - CGFloat(col) * squareSide/2 + CGFloat(row) * squareSide
let path = UIBezierPath()
path.move(to: CGPoint(x: topLeftX, y: topLeftY))
path.addLine(to: CGPoint(x: topLeftX + squareSide/2, y: topLeftY - squareSide/2))
path.addLine(to: CGPoint(x: topLeftX + squareSide/2, y: topLeftY + squareSide/2))
path.addLine(to: CGPoint(x: topLeftX, y: topLeftY + squareSide))
path.close()
path.fill()
path.stroke()
}
func drawTopParallelogram(col: Int, row: Int,color: CubeColor) {
colorOf(color: color).setFill()
let bottomLeftX: CGFloat = originX + CGFloat(col) * squareSide + CGFloat(2 - row) * squareSide/2
let bottomLeftY: CGFloat = originY + CGFloat(row - 2)*squareSide/2
let path = UIBezierPath()
path.move(to: CGPoint(x: bottomLeftX, y: bottomLeftY ))
path.addLine(to: CGPoint(x: bottomLeftX + squareSide/2,y: bottomLeftY - squareSide/2))
path.addLine(to: CGPoint(x: bottomLeftX + squareSide/2 + squareSide, y: bottomLeftY - squareSide/2))
path.addLine(to: CGPoint(x: bottomLeftX + squareSide, y: bottomLeftY))
path.close()
path.fill()
path.stroke()
}
func drawsquare(col: Int, row: Int,color: CubeColor) {
colorOf(color: color).setFill()
let squareX: CGFloat = originX + CGFloat(col) * squareSide
let squareY: CGFloat = originY + CGFloat(row) * squareSide
let square = UIBezierPath(rect: CGRect(x: squareX, y:squareY, width:squareSide, height:squareSide))
square.fill()
square.stroke()
}
func colorOf(color: CubeColor) -> UIColor {
var c: UIColor = .black
switch color {
case .blue:
c = UIColor.blue
case .green:
c = UIColor.green
case .orange:
c = UIColor.orange
case .red:
c = UIColor.red
case .white:
c = UIColor.white
case .yellow:
c = UIColor.yellow
}
return c
}
}
at "func drawFront() {" it said "Thread 1: breakpoint 1.1 (1)"
can any one help me fix this the app is always pausing
My app has a view that appears from a NavigationLink. The view has a list and a search bar; when a user taps the search bar the keyboard appears correctly. BUT, the entire view, including the navigationBarTitle and the navigationBarBackButton, move upward. This causes the navigationBarTitle and the navigationBarBackButton to move under the notch, where the back button doesn't work. To use the back button the user has to dismiss the keyboard with the return key, which moves the navigationBarTitle and back button downward and then tap the back button.
This cannot be an uncommon situation, but I've spent the morning trying to find a way to prevent the NavigationBarTitle and <back button from moving upward where the user can't use the <back button when the keyboard appears.
Is there a way to too that?
We have a teleprompter scrolling app that has worked fine up through OS Ventura. Now in Sonoma the text starts to slow down after 20-30 seconds, then if left alone ends up coming to a complete stop after 2-3 minutes and is frozen until we restart the scrolling.
An odd work around, not a fix, is that when we switch the display from dark mode to light mode it will restart the scrolling as if we manually stopped and restarted.
It was built in Swift Storyboard/Xcode 15 and we have been testing on MacBooks with Intel, Silicon, M1, M2 .
OS Sonoma is the only common denominator in which we experience the issue. We submitted a case to Apple yesterday but has anyone else experienced similar issues and heard of a fix?
Hi! While working on my Swift Student Challenge submission it seems that I found a race condition (TOCTOU) bug in SwiftUI when using sheets, and I'm not sure if this is expected behaviour or not.
Here's an example code:
import SwiftUI
struct ContentView: View {
@State var myVar: Int?
@State private var presentSheet: Bool = false
var body: some View {
VStack {
// Uncommenting the following Text() view will "fix" the bug (kind of, see a better workaround below).
// Text("The value is \(myVar == nil ? "nil" : "not nil")")
Button {
myVar = nil
} label: {
Text("Set value to nil.")
}
Button {
myVar = 1
presentSheet.toggle()
} label: {
Text("Set value to 1 and open sheet.")
}
}
.sheet(isPresented: $presentSheet, content: {
if myVar == nil {
Text("The value is nil")
.onAppear {
print(myVar) // prints Optional(1)
}
} else {
Text("The value is not nil")
}
})
}
}
When opening the app and pressing the open sheet button, the sheet shows "The value is nil", even though the button sets myVar to 1 before the presentSheet Bool is toggled.
Thankfully, as a workaround to this bug, I found out you can change the sheet's view to this:
.sheet(isPresented: $presentSheet, content: {
if myVar == nil {
Text("The value is nil")
.onAppear {
if myVar != nil {
print("Resetting View (TOCTOU found)")
let mySwap = myVar
myVar = nil
myVar = mySwap
}
}
} else {
Text("The value is not nil")
}
})
This triggers a view refresh by setting the variable to nil and then to its non-nil value again if the TOCTOU is found.
Do you think this is expected behaivor? Should I report a bug for this? This bug also affects .fullScreenCover() and .popover().
Hello! I have requested permission to participate in this years swift student challenge, but in the response is the link for the form for last years challenge.
Im making an app that uses drag&drop but, it doesn't work.
This is made with Swift Playground.
If you can find a solution, please let me know.
Here is the code.
//MARK: Drop Area
@ViewBuilder
func DropAera()->some View{
VStack(spacing: 12){
ForEach($rows,id:\.self){$row in
HStack(spacing: 10){
ForEach($row){$item in
Text(item.value)
.font(.system(size: item.fontSize))
.padding(.vertical,5)
.padding(.horizontal,item.padding)
.opacity(item.isShowing ? 1 : 0)
.background{
RoundedRectangle(cornerRadius: 6, style: .continuous)
.fill(item.isShowing ? .clear : .gray.opacity(0.25))
}
.background{
// If Item is Dropped into Correct Plase
RoundedRectangle(cornerRadius: 6, style: .continuous)
.stroke(.gray)
.opacity(item.isShowing ? 1 : 0)
}
// MARK: Adding Drop Operation
// MARK: Adding Drag Drop Operation
.onDrop(of: [.url], isTargeted: .constant(false)) {
providers in
if let first = providers.first{
let _ = first.loadObject(ofClass: URL.self) {
value,error in
guard let url = value else{return}
if item.id == "\(url)"{
droppedCount += 1
let progress = (droppedCount / CGFloat(characters.count))
withAnimation{
item.isShowing = true
updateShuffledArray(character: item)
self.progress = progress
}
}
else{
//Animating When Wrong text
animateView()
}
}
}
return false
}
}
}
if rows.last != row{
Divider()
}
}
}
}
@ViewBuilder
func DragArea()->some View{
VStack(spacing: 12){
ForEach(shuffledRows,id: \.self){row in
HStack(spacing: 10){
ForEach(row){item in
Text(item.value)
.font(.system(size: item.fontSize))
.padding(.vertical,5)
.padding(.horizontal,item.padding)
.background{
RoundedRectangle(cornerRadius: 6, style: .continuous)
.stroke(.gray)
}
// MARK: Adding Drag Drop Operation
.onDrag{
// Returning ID to find whitch Item is Moving
return .init(contentsOf: URL(string: item.id))!
}
.opacity(item.isShowing ? 0 : 1)
.background{
RoundedRectangle(cornerRadius: 6, style: .continuous)
.fill(item.isShowing ? .gray.opacity(0.25) : .clear)
}
}
}
if shuffledRows.last != row{
Divider()
}
}
}
}
Hello,
For the Swift Student Challenge, do I need to worry about submitting a clean source code with comments? Or does Apple judge submissions solely based on their user experience with the app?
Thanks!
Hi Developers,
I want to create a Vision app on Swift Playgrounds on iPad. However, Vision does not properly function on Swift Playgrounds on iPad or Xcode Playgrounds. The Vision code only works on a normal Xcode Project.
SO can I submit my Swift Student Challenge 2024 Application as a normal Xcode Project rather than Xcode Playgrounds or Swift Playgrounds File.
Thanks :)
I am currently working on a project for the Swift Student Challenge. One part of the app is for visualizing goals with a chart created using Swift Charts. In the app, you log your progress for the goal and then it should show up in the chart. My issue is that the data is not showing after it has been logged. Here are some code snippets:
Code For Chart View
Chart {
let currentDate = Date.now
BarMark (
x: .value("Day", "Today"),
y: .value("Score", goalItem.getLogItemByDate(date: currentDate).score)
)
}
.frame(maxHeight: 225)
.padding()
GoalItem Data Object
public class GoalItem: Identifiable {
public var id: String
var name: String
var description: String
var logItems: [String: GoalLogItem]
init(name: String, description: String) {
self.id = UUID().uuidString
self.name = name
self.description = description
self.logItems = [:]
}
func log(date: Date, score: Double, notes: String) {
self.logItems[dateToDateString(date: date)] = GoalLogItem(date: date, score: score, notes: notes)
}
func getLogItemByDate(date: Date) -> GoalLogItem {
let logItem = self.logItems[dateToDateString(date: date)]
if logItem != nil {
return logItem!
} else {
return GoalLogItem(isPlaceholder: true)
}
}
}
After logging something using the GoalItem.log method, why does it not show up in the chart? Are the variables not updated? If so, how would I get the variables to update?
Thanks
Hello,
Does anyone know how to restrict my app playground to run on iPhones only (not even iPads) and to always be presented in portrait mode? I'm using Xcode.
Thanks for any help!
Hello,
The appearance of one of my buttons is not updating after being tapped. I have had no trouble doing the exact same thing in my other views, but here it simply doesn't work. The "heart" button will keep its original appearance (in this case an unfilled heart) no matter what, despite my print statements indicating that the value has changed. The other actions performed when tapping the heart work perfectly. I've been at it for hours.
Any help would be appreciated. Thanks!
import SwiftUI
struct SearchView: View {
@State private var searchText = ""
@StateObject var save = SaveWords()
@State var heart: String?
@State var disappear = false
@State var done = true
var body: some View {
NavigationView {
VStack {
if !disappear {
SearchBarView(text: $searchText)
Spacer()
}
if searchText != "" {
List(.constant(Array(FetchWord.getWordFromStart(start: searchText)).prefix(10).map {Word(word: $0.1)})) { suggestion in
NavigationLink(destination: suggestion.IPA.wrappedValue == "error" ? AnyView(EmptyView()) : AnyView(PracticeView(wordSheet: suggestion)
.onAppear {
disappear = true
if done {
SaveWords.file = "Favorites"
DispatchQueue.main.async {
Task {
try? await save.load()
heart = save.words.contains(suggestion.wrappedValue) ? ".fill" : ""
}
}
}
}
.onDisappear {
disappear = false
Task {
SaveWords.file = "History"
try? await save.load()
if save.words.first != suggestion.wrappedValue {
save.words.insert(suggestion.wrappedValue, at: 0)
try? await save.save()
}
}
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
SaveWords.file = "Favorites"
done = false
if heart == "" {
heart = ".fill"
DispatchQueue.main.async {
Task {
try? await save.load()
if !save.words.contains(suggestion.wrappedValue) {
save.words.insert(suggestion.wrappedValue, at: 0)
try? await save.save()
}
}
}
} else {
heart = ""
DispatchQueue.main.async {
Task {
try? await save.load()
try? await save.delete(wordToDelete: suggestion.wrappedValue)
try? await save.save()
}
}
}
done = true
}, label: {
Image(systemName: "heart" + (heart ?? ""))
})
}
})
) {
if suggestion.IPA.wrappedValue != "error" {
CardView(wordSheet: suggestion)
}
}
}
}
}
Spacer()
}
}
}
#Preview {
SearchView()
}
Your app playground must be built with and run on Swift Playgrounds 4.4 or later (requires iPadOS 16 or macOS 13.5, or later) or Xcode 15 on macOS 13.5, or later. You may incorporate the use of Apple Pencil.
If I want to develop a playground for the iPad and Apple Pencil, am I limited to using Playgrounds on iPadOS to make it? Or could I also use Playgrounds on macOS and Xcode?
If I use Xcode to make my iPad playground, should I select "Xcode" for "Which software should we use to run your app playground?" I assume so, as I used Xcode to make my app — but then it will be run in a simulator by the judges, which means they cannot use the Apple Pencil.
I'm a little lost here. Any guidance is appreciated.
I am making a code that uses pencilKit and you can draw on the canvas. However, I want to be able to detect if the resulted drawing is in contact with a Rectangle().
Is there any way to do this?
I dont want to use variables for X and Y positions because I have more than 400 rectangles in a grid.
Is it possible to create SwiftData Document-based apps in App Playgrounds (or Swift Packages, since App Playgrounds are a special type of packages)?
As explained in wwdc2023-10154, to create a document-based app you are required to provide an UTType that conforms to com.apple.package. This requires your file type to be declared and exported in the Info.plist file of an Xcode project, but App Playgrounds don't have them.
Providing .package as a UTType seems to partially work:
import SwiftUI
import SwiftData
@main
struct SwiftDataFlashCardSample: App {
var body: some Scene {
#if os(iOS) || os(macOS)
DocumentGroup(editing: Card.self, contentType: .package) {
ContentView()
}
#else
WindowGroup {
ContentView()
}
.modelContainer(for: Card.self)
#endif
}
}
This way I am able to run the app, create and edit new document, and save it on disk. However, opening it again does not work (you cannot select it since it is a folder without a defined package type).
Is there any workaround to this?
I guess I could drop support for multiple documents entirely if this is not possible (I don't think this would affect my submission), but I would just like to check if there is any way to do this first.
I noticed updating a @Transient attribute's value does not refresh SwiftUI views when using a SwiftData model with @Query or @Bindable.
Here is a sample code (clicking the button changes the Transient attribute):
import SwiftUI
import SwiftData
// SwiftUI App struct declaration
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: MyModel.self)
}
}
// My SwiftData test model
@Model
class MyModel {
var myFirstArray: [Int]
@Transient var mySecondElement: Bool = false
init(myFirstArray: [Int] = [Int](), mySecondElement: Bool = false) {
self.myFirstArray = myFirstArray
self.mySecondElement = mySecondElement
}
}
// The SwiftUI View
struct ContentView: View {
@Query var myModels: [MyModel]
@Environment(\.modelContext) var modelContext
var body: some View {
VStack {
if myModels.count != 0 {
Text("Model:")
// I expected this to update when the button is clicked
Text("mySecondElement's value: \(myModels[0].mySecondElement ? "True" : "False" )")
Button {
// button that changes the transient attribute
myModels[0].mySecondElement.toggle()
print(myModels[0].mySecondElement) // this prints the actual value
} label: {
Text("Add mySecondElement data")
}
}
}
.onAppear {
try? modelContext.delete(model: MyModel.self)
if myModels.count == 0 {
let model = MyModel(myFirstArray: [0, 1, 3])
modelContext.insert(model)
}
}
}
}
I expected ContentView() to be refreshed when I clicked on the button. However, this seems to not be the case - it seems that attributes marked with @Transient don't publish updates to Views.
Is this expected behaviour? Should I file a bug / feedback for this?
Hello,
Very recently, the following code has automatically appeared at the bottom of three of my SwiftUI View files:
@available(iOS 17.0, macOS 14.0, tvOS 17.0, visionOS 1.0, watchOS 10.0, *)
struct $s10Accent_Ace33_0BADA584A03144EFDAB57154E6FD3FBALl7PreviewfMf_15PreviewRegistryfMu_: DeveloperToolsSupport.PreviewRegistry {
static let fileID: String = "Accent_Ace/HistoryView.swift"
static let line: Int = 47
static let column: Int = 1
static func makePreview() throws -> DeveloperToolsSupport.Preview {
DeveloperToolsSupport.Preview {
let randomWord1 = FetchWord.getRandomWord()
let randomWord2 = FetchWord.getRandomWord()
@State var randomWords = [Word(word: randomWord1.0, IPA: randomWord1.1, lineNumber: randomWord1.2), Word(word: randomWord2.0, IPA: randomWord2.1, lineNumber: randomWord2.2)]
HistoryView(words: $randomWords)
}
}
}
This is from one of my files but it's very similar in the other two. It seems to have something to do with my previews.
The problem is that this code generates an error: Ambiguous use of 'init(_:traits:body:)'. My previews worked just fine before the auto-generated code appeared, so I tried deleting it. However, it automatically comes back no matter how many times I get rid of it. It's preventing me from building my App Playground, so I can't run the app or even see the previews. Does anyone know how to get rid of it or fix the error?
Thanks for the help!
Hi, I am participating in the swift student challenge, and I need some help.
When I make a color by Color(red: , green: , blue: ), I calculate it by getting the rgb of the color that I want and dividing each of the colors by 255. For example, if red was 5, I would divide it by 255 to get 0.01960784313, which I put in the code for the red parameter. However, when I run the code, the color that appears is a bit different than the one I was expecting to see. Can someone please explain this?
Hello, is the new Journaling Suggestions API available in App Playgrounds (made using Xcode)?
I know I can add capabilities in Xcode, but it seems that the Journaling Suggestions capability isn't available. I assume this API is currently unsupported in App Playgrounds?