Post

Replies

Boosts

Views

Activity

Symbol navigator is polluted with thousands of system classes!
I have a test app. I added some extension classes to one of source code like below: extension String { func addPathComponent(_ path: String) -> String { return (self as NSString).appendingPathComponent(path) } func sameText(with: String) -> Bool { return self.caseInsensitiveCompare(with) == .orderedSame } var isBlank: Bool { allSatisfy { $0.isWhitespace } } } extension Optional where Wrapped == String { var isBlank: Bool { self?.isBlank ?? true } } Now the symbol navigator is polluted with many system classes: BTW, I am using Xcode 14.3.1.
1
0
620
Sep ’23
Need help on Array and API design
I am working on an app which I plan to submit to App Store in 2 weeks. Now I have a headache with Array type. I have the following API design in my app: class SomeParser { func getTranslations(_ locale: String) -> [TranslationUnit]? { // Check if the locale units are already in a cache, if not build a new list // and return the list } } class MainVC { func doTranslation() { var list = parser.getTranslation("en") // Modify some units in the list. // How to put it back to cache? } } Now the problem is that since Array is a value type, the modified list is isolated. The only way to reflect the changes into cache is put the modified list back to cache: translationCache[locale] = modifiedList But this is counter-intuitive and waste of performance. Is there anyway to workaround this problem?
1
0
409
Oct ’23
Need help on generics where clause
I have the following class: /// Act as a reference container for value types. public class ValueBox<ValueType: ??> { public var value: ValueType public init() { value = ValueType() // Compiler error } public init(_ value: ValueType) { self.value = value } } Is it possible to specify the generic type ValueType can be inited?
1
0
306
Oct ’23
Weird error with HTTPS connection
I have a weird problem with HTTPS connection. Task <A19A5441-F5CD-4F8C-8C88-73FC679D8AE0>.<1> finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." I am trying to bypass server certificate of my website because it's self-signed. The following code works in a test app, but not in another app. They have exactly have the same entitlements: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>com.apple.security.app-sandbox</key> <true/> <key>com.apple.security.files.user-selected.read-write</key> <true/> <key>com.apple.security.network.client</key> <true/> </dict> </plist> func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let protectionSpace = challenge.protectionSpace guard protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, protectionSpace.host.contains("mywebsite.net") else { completionHandler(.performDefaultHandling, nil) return } guard let serverTrust = protectionSpace.serverTrust else { completionHandler(.performDefaultHandling, nil) return } let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) } @IBAction func testMenuItem_select(_ sender: Any) { print("\(sender)") Preferences.instance.openTipShowed = false testURLSession() func testURLSession() { let session = URLSession(configuration: URLSessionConfiguration.ephemeral, delegate: self, delegateQueue: nil) let url2 = "https://www.mywebsite.net/spiders.txt" let url3 = "https://www.apple.com/" let url = URL(string: url2)! var request = URLRequest(url: url) let task = session.dataTask(with: request) { data, response, error in if let error { print(error) } if let data { let text = String(data: data, encoding: .utf8) print("HTTP response object:", response ?? "") print("HTTP resonse text:", text ?? "<empty response>") } } task.resume() } }
1
0
711
Oct ’23
PropertyListDecoder and .strings file
I have the following code: let file = "/path/to/en.lproj/Localizable.strings" let dec = PropertyListDecoder() var f: PropertyListSerialization.PropertyListFormat = .openStep do { //let data = strings.data(using: .utf8)! let data = try Data(contentsOf: URL(fileURLWithPath: file)) let list = try dec.decode([String: String].self, from: data, format: &f) print("foramt:", f.rawValue) list.forEach { print($0.key, $0.value) } } catch { print(error) } It seems PropertyListDecoder can correctly decode .strings file format; detected format is openStep (value is 1). But I am note sure because I couldn't find any docs on PropertyListDecoder about .strings file. Can anyone confirm this?
1
0
443
Oct ’23
Weird problem of NSTableView with auto layout
I have had this issue for a long time. If I configure any auto layout constraints in TableViewCell, I get extremely weird layout behavior in IB designer; however, layout is completely good during runtime. For example, with a completely new project and a single NSTableView on the main view, I get: If I resize main view, the tableview won't get resized Every time I reopen the project, the tableview would shrink by height. It seems the shrinked height is doubled every time. For example, in the following screenshot, the gap is 56. Next reopen will double the gap to 112. Is this a known bug? I would want to file bug report at https://feedbackassistant.apple.com.
1
1
654
Nov ’23
How read image file metadata?
I want to read metadata of image files such as copyright, author etc. I did a web search and the closest thing is CGImageSourceCopyPropertiesAtIndex: - (void)tableViewSelectionDidChange:(NSNotification *)notif { NSDictionary* metadata = [[NSDictionary alloc] init]; //get selected item NSString* rowData = [fileList objectAtIndex:[tblFileList selectedRow]]; //set path to file selected NSString* filePath = [NSString stringWithFormat:@"%@/%@", objPath, rowData]; //declare a file manager NSFileManager* fileManager = [[NSFileManager alloc] init]; //check to see if the file exists if ([fileManager fileExistsAtPath:filePath] == YES) { //escape all the garbage in the string NSString *percentEscapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)filePath, NULL, NULL, kCFStringEncodingUTF8); //convert path to NSURL NSURL* filePathURL = [[NSURL alloc] initFileURLWithPath:percentEscapedString]; NSError* error; NSLog(@"%@", [filePathURL checkResourceIsReachableAndReturnError:error]); //declare a cg source reference CGImageSourceRef sourceRef; //set the cg source references to the image by passign its url path sourceRef = CGImageSourceCreateWithURL((CFURLRef)filePathURL, NULL); //set a dictionary with the image metadata from the source reference metadata = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(sourceRef,0,NULL); NSLog(@"%@", metadata); [filePathURL release]; } else { [self showAlert:@"I cannot find this file."]; } [fileManager release]; } Is there any better or easy approach than this?
1
0
958
Dec ’23
Environment variable not working in another user account
I have the following in my .zshrc: export MY_LIBRARY_DIR=~/bin In Xcode I can set header/lib search path using something like $(MY_LIBRARY_DIR)/abc. This works fine in my daily used user account. But today I found that this technique does not work in a test user account (for testing purpose only). I even reboot my machine but still can't get it working. Am I missing something very obvious??? BTW, I am using Xcode 14.2 and 14.3.1.
1
0
721
Dec ’23
@escaping vs @nonescaping closures
I know this is a frequently asked question, but... After reading many articles on the net, I am still not sure if I have a solid understanding of the logics behind the design. One of my puzzles around this question is - Is the Swift compiler clever enough so that I can solely rely on its warnings/errors?
1
0
778
Jan ’24