@IBOutlet weak var surnameTextField: UITextField!
surnameTextField.backgroundColor = UIColor.clear
surnameTextField.tintColor = .white
surnameTextField.textColor = .white
surnameTextField.attributedPlaceholder = NSAttributedString(string: surnameTextField.placeholder!, attributes: [NSAttributedString.Key.foregroundColor: UIColor(white: 1.0, alpha: 0.6)])
let bottomLayersurname = CALayer()
bottomLayersurname.frame = CGRect(x: 0, y: 29, width:1000, height: 0.6)
bottomLayersurname.backgroundColor = UIColor.lightGray.cgColor
surnameTextField.layer.addSublayer(bottomLayersurname)
Dive into the world of programming languages used for app development.
Post
Replies
Boosts
Views
Activity
Hello togehter,
i do have the following question.
If I have my App run in landscape mode and a sheet view get's called, will it be possible to switch automatically from landscape mode in portrait mode and fix this device orientation?
Once the sheet view get's dismissed or closed, the original view will come back and the device orientation shall switch back to landscape mode.
Thanks you so much for your help!
Some of my users reported they can not completed the purchase .
According to the logs and screen captures . Their purchase progress's last status are "purchasing"
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
....
....
case .purchasing:
// 处理正在购买的情况
//print("购买中");
AppDelegate.log.debug("paymentQueue purchasing");
LoadingAlert.shared.setText(text: "购买中".localized())
....
After this ,It neither entered any error branch nor prompted the user to confirm the purchase or enter a password, but simply stopped here. There are no other purchase-related logs, and the program is still running normally.
At the same time, other users are able to complete their purchases without any issues. However, there have been 4-5 users recently who reported problems with purchasing. What could be the possible reasons?
In my local environment, I repeated the test many times, including using sandbox users from different regions and real Apple IDs, and everything worked fine.
//
// Payment.swift
// RadialMenu
//
// Created by pat on 2023/6/26.
//
import Foundation
import StoreKit
class Payment:NSObject,SKProductsRequestDelegate,SKPaymentTransactionObserver{
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
AppDelegate.log.debug("paymentQueue transaction product = \(transaction.payment.productIdentifier) state = \(transaction.transactionState)");
//let productID = transaction.payment.productIdentifier
switch transaction.transactionState {
case .purchased,.restored:
if(transaction.transactionState == .purchased){
AppDelegate.log.debug("paymentQueue purchased");
LoadingAlert.shared.setText(text: "已购买".localized())
}
if(transaction.transactionState == .restored){
LoadingAlert.shared.setText(text: "已恢复".localized())
AppDelegate.log.debug("paymentQueue restored");
}
//}
break;
case .failed:
AppDelegate.log.debug("paymentQueue failed ");
if let error = transaction.error as? NSError {
// 获取错误代码和描述
let errorCode = error.code
let errorDescription = error.localizedDescription
AppDelegate.log.debug("paymentQueue Transaction failed with error code: \(errorCode), description: \(errorDescription)")
}
queue.finishTransaction(transaction)
LoadingAlert.shared.hideModal();
// 处理购买失败的情况
// 提供错误信息给用户
//print("购买失败");
alertRetry();
break;
case .deferred:
AppDelegate.log.debug("paymentQueue deferred");
LoadingAlert.shared.setText(text: "购买延迟".localized())
// 处理交易延迟的情况(仅限家庭共享)
break;
case .purchasing:
// 处理正在购买的情况
//print("购买中");
AppDelegate.log.debug("paymentQueue purchasing");
LoadingAlert.shared.setText(text: "购买中".localized())
break;
@unknown default:
AppDelegate.log.debug("paymentQueue nknown default\(transaction.transactionState)");
break
}
}
}
NSPredicate(format: "SELF MATCHES %@", "^[0-9A-Z]+$").evaluate(with: "126𝒥ℰℬℬ𝒢𝒦𝒮33")
Returns true, and I don't know why. 𝒥ℰℬℬ𝒢𝒦𝒮 is not between 0-9 and A-Z, and why it returns true? How to avoid similar problem like this when using NSPredicate?
I have configured DateFormatter in the following way:
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
df.locale = .init(identifier: "en")
df.timeZone = .init(secondsFromGMT: 0)
in some user devices instead of ISO8601 style it returns date like 09/25/2024 12:00:34
Tried to change date format from settings, changed calendar and I think that checked everything that can cause the problem, but nothing helped to reproduce this issue, but actually this issue exists and consumers complain about not working date picker.
Is there any information what can cause such problem? May be there is some bug in iOS itself?
I found a similar problem here https://developer.apple.com/forums/thread/764777 and I could solve my problem by wrapping the call to requestAutomaticPassPresentationSuppression in a call to DispatchQueue.global().async.
But my question is if this is really how things should work. Even with strict concurrency warnings in Swift 6 I don't get any warnings. Just a runtime crash.
How are we supposed to find these problems? Couldn't the compiler assist with a warning/error.
Why does the compiler make the assumptions it does about the method that is declared like this:
@available(iOS 9.0, *)
open class func requestAutomaticPassPresentationSuppression(responseHandler: @escaping (PKAutomaticPassPresentationSuppressionResult) -> Void) -> PKSuppressionRequestToken
Now that we have migrated to Swift 6 our code base contains a bunch of unknown places where it will crash as above.
After ther Mac application is launched:
Log error: CGSWindowShmemCreateWithPort failed on port 0
and when the application quit:
No error handler for XPC error: Connection invalid
Appear with Xcode 15.4 but not with 12.4
As repported by Steve4442 in "Can someone explain this message" https://Forums.Developer.Apple.com/Forums/Thread/727803
.
The code don't use "windowNumbersWithOptions"
Can I ignore this log message ?
❌ Could not find email_ai.py in the app bundle. Available files: []
The error above is what I’m encountering.
I’ve placed the referenced file both in the project directory and inside the app. However, every time I remove and reinsert the file into the folder within the app, it prompts me to designate the targets—I select all, but this doesn’t resolve the issue.
I’m unsure how to properly reference the file so that it is recognised and included in the bundle. Any guidance would be greatly appreciated.
this is my build phase:
#!/bin/sh
set -x # Prints each command before running it (for debugging)
pwd # Shows the current working directory
echo "$SRCROOT" # Shows what Xcode thinks is the project root
ls -l "$SRCROOT/EmailAssistant/EmailAssistant/PythonScripts" # Lists files in the script folder
export PYTHONPATH="/Users/caesar/.pyenv/versions/3.11.6/bin"
/Users/caesar/.pyenv/versions/3.11.6/bin/python3 "$SRCROOT/EmailAssistant/EmailAssistant/PythonScripts/email_ai.py"
echo "Script completed."
For my app I've created a Dictionary that I want to persist using AppStorage
In order to be able to do this, I added RawRepresentable conformance for my specific type of Dictionary. (see code below)
typealias ScriptPickers = [Language: Bool]
extension ScriptPickers: @retroactive RawRepresentable where Key == Language, Value == Bool {
public init?(rawValue: String) {
guard let data = rawValue.data(using: .utf8),
let result = try? JSONDecoder().decode(ScriptPickers.self, from: data)
else {
return nil
}
self = result
}
public var rawValue: String {
guard let data = try? JSONEncoder().encode(self), // data is Data type
let result = String(data: data, encoding: .utf8) // coerce NSData to String
else {
return "{}" // empty Dictionary represented as String
}
return result
}
}
public enum Language: String, Codable, {
case en = "en"
case fr = "fr"
case ja = "ja"
case ko = "ko"
case hr = "hr"
case de = "de"
}
This all works fine in my app, however trying to run any tests, the build fails with the following:
Conflicting conformance of 'Dictionary<Key, Value>' to protocol 'RawRepresentable'; there cannot be more than one conformance, even with different conditional bounds
But then when I comment out my RawRepresentable implementation, I get the following error when attempting to run tests:
Value of type 'ScriptPickers' (aka 'Dictionary<Language, Bool>') has no member 'rawValue'
I hope Joseph Heller is out there somewhere chuckling at my predicament
any/all ideas greatly appreciated
I notice that Swift Data type's hashValue collision when first 80 byte of data and data length are same because of the Implementation only use first 80 bytes to compute the hash.
https://web.archive.org/web/20120605052030/https://opensource.apple.com/source/CF/CF-635.21/CFData.c
also, even if hash collision on the situation like this, I can check data is really equal or not by ==
does there any reason for this implementation(only use 80 byte of data to make hashValue)?
test code is under below
let dataArray: [UInt8] = [
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
]
var dataArray1: [UInt8] = dataArray
var dataArray2: [UInt8] = dataArray
dataArray1.append(contentsOf: [0x00, 0x00, 0x00, 0x00])
dataArray2.append(contentsOf: [0xff, 0xff, 0xff, 0xff])
let data1 = Data(dataArray1)
let data2 = Data(dataArray2) // Only last 4 byte differs
print(data1.hashValue)
print(data2.hashValue)
print(data1.hashValue == data2.hashValue) // true
print(data1 == data2) // false
Hi the below array and code to output a list item works fine:
var quotes = [
[
"quote": "I live you the more ...",
"order": "1"
],
[
"quote": "There is nothing permanent ...",
"order": "2"
],
[
"quote": "You cannot shake hands ...",
"order": "3"
],
[
"quote": "Lord, make me an instrument...",
"order": "4"
]
]
cell.textLabel?.text = quotes[indexPath.row]["quote"]
However if I change the "order" values to be numbers rather than text like below then for the above line I get an error message in Xcode "No exact matches in call to subscript". Please could someone tell me how to make it work with the numbers stored as numbers? (I'm wondering if creating an any array type and using the .text function has caused a conflict but I can't find how to resolve)
[
"quote": "I live you the more ...",
"order": 1
],
[
"quote": "There is nothing permanent ...",
"order": 2
],
[
"quote": "You cannot shake hands ...",
"order": 3
],
[
"quote": "Lord, make me an instrument...",
"order": 4
]
]
Thank you for any pointers :-)
The following code works when compiling for macOS:
print(NSMutableDictionary().isEqual(to: NSMutableDictionary()))
but produces a compiler error when compiling for iOS:
'NSMutableDictionary' is not convertible to '[AnyHashable : Any]'
NSDictionary.isEqual(to:) has the same signature on macOS and iOS. Why does this happen? Can I use NSDictionary.isEqual(_:) instead?
I am encountering a strange issue. I have a class that manages a selection of generic items T in an Array. It's a work in progress, but I'l try to give a gist of the setup.
class FileManagerItemModel: NSObject, Identifiable, Codable, NSCopying, Transferable, NSItemProviderReading, NSItemProviderWriting {
var id: URL
static func == (lhs: FileManagerItemModel, rhs: FileManagerItemModel) -> Bool {
lhs.fileURL == rhs.fileURL
}
var fileURL: URL {
FileManagerItemModel.normalizedFileURL(type: type,
rootURL: rootURL,
filePath: filePath)
}
init(type: FileManagerItemType, rootURL: URL, fileURL: URL) {
self.type = type
self.rootURL = rootURL
self.filePath = FileManagerItemModel.filePathRelativeToRootURL(fileURL: fileURL, rootURL: rootURL) ?? "[unknown]"
self.id = FileManagerItemModel.normalizedFileURL(type: type,
rootURL: rootURL,
filePath: filePath)
}
}
The class that manages the selection of these FileManagerItemModels is like so:
@Observable
class MultiSelectDragDropCoordinator<T: Hashable>: ObservableObject, CustomDebugStringConvertible {
private(set) var multiSelectedItems: [T] = []
func addToSelection(_ item: T) {
if !multiSelectedItems.contains(where: { $0 == item }) {
multiSelectedItems.append(item)
}
}
...
}
My issue is that the check if !multiSelectedItems.contains(where: { $0 == item }) in func addToSelection fails. The if is always executed, even if multiSelectedItems contains the given item.
Now, my first thought would be to suspect the static func == check. But that check works fine and does what it should do. Equality is defined by the whole fileURL.
So, the if should have worked. And If I put a breakpoint in func addToSelection on the if, and type po multiSelectedItems.contains(where: { $0 == item }) in the debug console, it actually returns true if the item is in multiSelectedItems. And it properly return false if the item is not in multiSelectedItems.
Still, if I then continue stepping through the app after the breakpoint was hit and I confirmed that the contains should return true, the app still goes into the if, and adds a duplicate item.
I tried assigning to a variable, I tried using a function and returning the true/false. Nothing helps.
Does anyone have an idea on why the debugger shows one (the correct and expected) thing but the actual code still does something different?
Does anyone know if there will be a Swift 6 version of "The Swift Programming Language" book and if so, when it will be released for Apple Books?
Hi I'm new here - I'm trying to learn Swift and SwiftUI.
Tried on PluralSight and Udemy but they have been outdated and thus hard to follow.
So after finding Apples own guides I felt relieved and happy, but now I'm stuck again.
After they've updated Xcode to use #Preview instead of PreviewProvider it's hard to follow along on their tutorial.
Does anyone know of good resources to study SwiftUI? Or know if apple plan to update their tutorials any time soon?
I'm here now if anyone's interested or it's useful information: https://developer.apple.com/tutorials/app-dev-training/managing-state-and-life-cycle
Hello everyone,
There is one thing about Objective-C's memory management that confuses me, which is a returned object's lifetime from methods with names doesn't start with "alloc", "new", "copy", or "mutableCopy".
Take this as an example, when using NSBitmapImageRep's representationUsingType:properties: method, it returns an NSData object (reference: https://developer.apple.com/documentation/appkit/nsbitmapimagerep/representation(using:properties:)?language=objc).
While testing this out, the NSData seemed to be an owned object (it doesn't get released until the end of the program).
From what I understand, this may be an auto-released object which is released at the end of an autorelease pool block.
Could someone explain this in more detail? What if I want to release that NSData object before the end of the autorelease pool block? How can I know which object is autoreleased, borrowed, or owned?
I've created a Julia interface for Apple Accelerate's libSparse, via calling the library functions as if they were C (@ccall). I'm interested in using this in the context of power systems, where the sparse matrix is the Jacobian or the ABA matrix from a sparse grid network. However, I'm puzzled by the performance.
I ran a sampling profiler on repeated in-place solves of Ax = b for a large sparse matrix A and random dense vectors b. (A is size 30k, positive definite so Cholesky factorization.) The 2 functions with the largest impact are _SparseConvertFromCoordinate_Double from libSparse.dylib, and BLASStateRelease from libBLAS.dylib. That strikes me as bizarre. This is an in-place solve: there should be minimal overheard from allocating/deallocating memory. Also, it seems strange that the library would repeatedly convert from coordinate form. Is this expected behavior?
Thinking it might be an artifact of the Julia-C interface, I wrote up a similar program in C/Objective-C. I didn't profile it, but timing the same operation (repeated in-place solves of Ax = b for random vectors b, with the same matrix A as in the Julia) gave the same duration. I've attached the C/Objective-C below.profiling-comparison.m.txt
If you're familiar with Julia, the following will give you the matrix I was working with:
using PowerSystems, PowerNetworkMatrices
sys = System("pglib_opf_case30000_goc.m")
A = PowerNetworkMatrices.ABA_Matrix(sys).data
where you can find the .m file here. (As a crude way to transfer A from Julia to C, I wrote the 3 arrays A.nzval, A.colptr, and A.rowval to .txt files as space-separated lists of numbers: the above C/objective-C reads in those files.) To duplicate my Julia profiling, do pkg> add AppleAccelerate#libSparse Profile--note the #libSparse part, these features aren't on the main branch--then run
using AppleAccelerate, Profile
# run previous code snippet to define A
M, N = 10000, size(A)[1]
bs = [rand(N) for _ in 1:M]
aa_fact = AAFactorization(A)
factor!(aa_fact)
solve!(aa_fact, bs[1]) # pre-compile before we profile.
Profile.init(n = 10^6, delay = 0.0003)
@profile (for i in 1:M; solve!(aa_fact, bs[i]); end;)
Profile.print(C = true, format = :flat, sortedby = :count)
decidePolicyFor delegate method:
import WebKit
@objc extension DocumentationVC
{
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
Being called just alright in swift 5 minimal concurrency.
Raising concurrency to complete with swift 5 or swift 6. Changing the code to avoid warnings:
@preconcurrency import WebKit
@objc extension DocumentationVC
{
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
The delegate method is not being called. Changing back to swift 5 concurrency minimal - it is called.
Looking at WKNavigationDelegate:
WK_SWIFT_UI_ACTOR
@protocol WKNavigationDelegate <NSObject>
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(WK_SWIFT_UI_ACTOR void (^)(WKNavigationActionPolicy))decisionHandler WK_SWIFT_ASYNC(3);
Changing the delegate method to:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
And it is called across swift 5 concurrency minimal to complete to swift 6.
I thought, the meaning of @preconcurrency import WebKit was to keep the delegate without @MainActor before the (WKNavigationActionPolicy) still matching regardless the swift concurrency mode?
My point is - this can introduce hidden breaking changes? I didn't see this documented anyhow at: https://www.swift.org/migration/documentation/migrationguide/.
decidePolicyFor is an optional method - so if signature 'mismatches' - there will be no warning on not-implementing the delegate method.
How do we catch or diagnose irregularities like this? Is it something @preconcurrency import WebKit should be ensuring and it is not?
Is this delegate mismatch a bug on swift side or something we should be taking care of while migrating? If it is on us, how do we diagnose these potential mismatches?
I've got a watch app, still with storyboard, WKInterfaceController and WatchConnectivity.
After updating it for swift 6 concurrency I thought I'd keep it for a little while without swift 6 concurrency dynamic runtime check.
So I added -disable-dynamic-actor-isolation in OTHER_SWIFT_FLAGS, but it doesn't seem to have an effect for the Apple Watch target. Without manually marking callbacks where needed with @Sendable in dynamic checks seem to be in place.
swiftc invocation is as (includes -disable-dynamic-actor-isolation):
swiftc -module-name GeoCameraWatchApp -Onone -enforce-exclusivity\=checked ... GeoCameraWatchApp.SwiftFileList -DDEBUG -enable-bridging-pch -disable-dynamic-actor-isolation -D DEBUG -enable-experimental-feature DebugDescriptionMacro -sdk /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS11.2.sdk -target arm64_32-apple-watchos7.0 -g -module-cache-path /Users/stand/Library/Developer/Xcode/DerivedData/ModuleCache.noindex -Xfrontend -serialize-debugging-options -enable-testing -index-store-path /Users/stand/Library/Developer/Xcode/DerivedData/speedo-almhjmryctkitceaufvkvhkkfvdw/Index.noindex/DataStore -enable-experimental-feature OpaqueTypeErasure -Xcc -D_LIBCPP_HARDENING_MODE\=_LIBCPP_HARDENING_MODE_DEBUG -swift-version 6
...
-disable-dynamic-actor-isolation flag seems to be working for the iOS targets, I believe.
The flag is described here
Am I missing something? Should the flag work for both iOS and Apple Watch targets?
Hello Apple Team,
I'm trying to import the Audodesk FBX SDK to my Objective-C iOS Project.
The SDK is written in C++, but has support for iOS and the iOS simulator architectures.
I've added the path to the include folder in the Header Search Path
I've also added the paths to libfbxsdk.a in the Library Search Paths
Finally, I've added the libfbxsdk.a file to the Link Binary with Libraries.
However, when I build the project, I get the following error:
building for 'iOS', but linking in object file (/Users/Lond/Documents/v2/Autodesk/iOS/2020.3.7/lib/ios/debug/libfbxsdk.a[28](fbxalloc.cxx.o)) built for 'macOS'
In the terminal, if I type the command:
lipo -info libfbxsdk.a
I get the message
Non-fat file: libfbxsdk.a is architecture: arm64
confirming that I'm using the library for the correct architecture.
Do I need to add any other confifuration option? (Like the other linker flag or something else)
I'm quite new to C++, and integrating a C++ SDK into iOS is not easy.
I'm using Mac Os Sonoma 14.6.1
Tested on Xcode 15.4 and 16.2
Target Device: iPhone 13 Pro (iOS 17.6.1)
iOS FBX SDK version: 2020.3.7
Link to the SDK if needed:
https://aps.autodesk.com/developer/overview/fbx-sdk
Any help would be greatly appreciated
Thank you