error 'value of type Realm.Configuration' has no member path', swift 2.2 - swift2

I have a red alert error 'value of type 'Realm.Configuration 'has no member 'path'.
I have not yet run the project as I'm building it, copying files and settings exactly from another project which has realm running fine.
Any ideas?
The error is on the line
print(Realm.Configuration.defaultConfiguration.path!)
it is on my MapViewController (a long swift file with a lot of code so I'm not sure which part to copy here. The top of the file has 'import RealmSwift', which is in my pod file.
the code block is
override func viewDidLoad() {
super.viewDidLoad()
title = "Map"
locationManager.delegate = self
if CLLocationManager.authorizationStatus() == .NotDetermined {
locationManager.requestWhenInUseAuthorization()
} else {
locationManager.startUpdatingLocation()
}
print(Realm.Configuration.defaultConfiguration.path!)
populateMap()
}

The Realm.Configuration.path property was changed from a String? to a fileURL: NSURL? property in Realm 0.99.0. It's likely that you're using a more recent version of Realm than that, which removed the path property.
So change path to fileURL.

Try to use
Realm.Configuration.defaultConfiguration.fileURL!

Related

archive error: "xxx-master.dia:1:1: Could not read serialized diagnostics file: Cannot Load File: Failed to open diagnostics file"

I upgraded my xcode to 11.4 yesterday, now I can not archive my SwiftUI code to submit appstore, because error: "error: Segmentation fault: 11", "xxx-master.dia:1:1: Could not read serialized diagnostics file: Cannot Load File: Failed to open diagnostics file".
Any advices?
I root caused my occurrence of this error to usage of 'Self' in a class func for a XIB UIView. The error happened for me in XCode 11.5 and only the release build of the project. So, looks like the issue is in -O compilation. (It looks like the academic project named Swift has rediscovered the useful concept of Self)
THE EXAMPLE BELOW CAUSES segfault 11, FIXED BY REPLACING THE THREE "Self" WITH CLASS NAME "StyleHSView":
class StyleHSView: UIStackView, UITextFieldDelegate {
#IBOutlet weak var styleNameTF: UITextField!
#IBOutlet weak var urlTF: UITextField!
// THIS FUNC CAUSES segfault 11, fix by changing Self to class name StyleHSView.
class func Instantiate() -> Self {
let nib = UINib.init(nibName: "StyleHSView", bundle: nil)
if let view = nib.instantiate(withOwner: nil, options: nil).first(where: { return $0 is Self }) as? Self
{
return view
} else {
fatalError("No StyleHSView")
}
}
}
Similar to the experience of this commenter in the issue #foolbear commented above, this was caused by a modifier one of my views.
In my case, I was using an Introspect modifier on a UIViewRepresentable.
In the stack dump of your error, identify the view where the issue is happening and try removing view modifiers until the error goes away.

Swift 4.2.1 requesting JSON with Xcode 10.1

My code:
let cgpurl = URL(string: "https://api.coingecko.com/api/v3/ping")!
let task = URLSession.shared.dataTask(with: cgpurl) { (Data, URLResponse, Error) in
if let data = Data, let string = String(data: data, encoding: .utf8) {
let CGPing = string } ; resume() }
The problem is with the 2nd use of "cgpurl". I've tried changing case to no effect. The error I'm getting is, "Cannot use instance member 'cgpurl' within property initializer; property initializers run before 'self' is available". Ok... but I can't even replace cgpurl with the actual link? Then I get the error message "Ambiguous reference to member 'dataTask(with:completionHandler:)'" I realize this release of swift was supposed to be "small" & just to "fix errors" but I've not been able to find any current documentation on this release. I'm using swift 4.2.1 with Xcode 10.1
This code was taken directly from a teaching manual for Swift 4.2
No, it wasn't. The code you have was never right, in Swift 4.2 or any other version of Swift. You have blindly copied and pasted perhaps, without looking at the overall context.
The problem is that the code, as you have it, is sitting "loose" at the top of your view controller or other class declaration, perhaps something along these lines:
class MyViewController : UIViewController {
let cgpurl = // ...
let task = // ...
}
That's wrong. The most basic rule of Swift programming is that executable code can exist only in a function. For example:
class MyViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let cgpurl = // ...
let task = // ...
}
}
That may not solve all your issues, but at least you'll get past the most basic mistake you're making and the "Cannot use instance member" compile error will go away.

How to associate existing file type for Mac OS application in XCode 7?

I am making a simple viewer for jpeg pictures in Xcode 7, and trying to associate Jpeg file type with my application. This is a Cocoa application for OS X in Swift that uses storyboards, and is not a document-based application.
Tutorials that I found online suggest going through Info tab, adding a new document type there. Now that's where things start to look different from those in tutorials: in them there is only 3 field to fill out (Name, Types, Icon), but I have many more. I tried to experiment around and here is what I put in fields that I got:
Name: JPEG image
Class: left it blank
Extensions: .jpg, .jpeg, .JPEG, .JPG
Icon: left it blank
Identifier: public.jpeg
Role: Viewer
Mime types: image/jpeg
"Document is distributed as a bundle" is partially checked by default; I just left it as is.
Did not touch additional document type properties either.
As a result I got my application showing in a list in "Open with" when I secondary-click a Jpeg file along with other installed applications, but once I try to open it that way, I get a popup saying The document "picture.jpg" could not be opened. MyApp cannot open files in the "JPEG image" format.
What am I doing wrong?
The Class field is compulsory, and you have to have corresponding implementation.
Try:
Class: $(PRODUCT_MODULE_NAME).Document
And then add the Document.swift:
import Cocoa
class Document : NSDocument
{
override init() {
super.init()
// Add your subclass-specific initialization here.
}
override class func autosavesInPlace() -> Bool {
return true
}
override func makeWindowControllers() {
// Returns the Storyboard that contains your Document window.
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let windowController = storyboard.instantiateController(withIdentifier: "Document Window Controller") as! NSWindowController
self.addWindowController(windowController)
}
override func data(ofType typeName: String) throws -> Data {
// Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil.
// You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
override func read(from data: Data, ofType typeName: String) throws {
// Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
// You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
// If you override either of these, you should also override -isEntireFileLoaded to return false if the contents are lazily loaded.
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
}
^ Modify as you need.
Also, you specified the role "Viewer", means you can open it with the space bar, and not the double click (open) - which is the role "Edit" right?

What is the correct way to use backgroundCompletionHandler in Alamofire?

I'm not clear on how to use this properly but had seen other people doing this type of thing:
func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) {
manager.sharedInstance.backgroundCompletionHandler = completionHandler
}
In our similar implementation, at this point completionHandler is partial apply forwarder for reabstraction thunk helper...
Where manager is (despite being a singleton) essentially:
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.ourcompany.app")
let manager = Alamofire.Manager(configuration: configuration)
However this causes the following warning to be printed in the console:
Warning: Application delegate received call to -application:handleEventsForBackgroundURLSession:completionHandler: but the completion handler was never called.
I set a breakpoint here and at this point the message is already visible in the console and backgroundCompletionHandler is nil.
We're building against the iOS 9 SDK with Xcode 7.0 and currently using Alamofire 2.0.2
I originally thought this was introduced when we merged our Swift 2.0 branch but I'm also seeing the message with an earlier commit using Xcode 6.4 against the iOS 8 SDK.
Update 1
To address #cnoon's suggestions:
The identifier matches - the configuration and manager are set inside a singleton so there's no way for it to be wrong.
When adding and printing inside of didSet on backgroundCompletionHandler in the Manager class, the message is logged before the warning.
When printing inside of the closure set to sessionDidFinishEventsForBackgroundURLSession on the delegate inside the Manager class, the message is printed after the warning.
When overriding sessionDidFinishEventsForBackgroundURLSession and printing inside of it before calling backgroundCompletionHandler, the message is printed after the warning.
As for verifying I have my Xcode project set up correctly for background sessions, I'm not sure how to do that and couldn't find any documentation on how to do so.
I should note that when trying to upload some screenshots from my phone I was initially unable to reproduce this issue in order to try these suggestions.
It was only after trying to share some photos that I was able to reproduce this again. I'm not sure or the correlation (if any) but it may be related to the photos taking longer to upload.
Update 2
The UIBackgroundModes are set exactly as #Nick described, and calling completionHandler() directly inside of application:handleEventsForBackgroundURLSession:completionHandler: does not display the warning.
Update 3
So, it appears I overlooked an small but important detail. There's a wrapper around Alamofire.Manager that doesn't expose it directly. The relevant part of its implementation looks like this:
private var manager: Manager
public var backgroundCompletionHandler: (() -> Void)? {
get {
return manager.backgroundCompletionHandler
}
set {
manager.backgroundCompletionHandler = backgroundCompletionHandler
}
}
and setting the completion handler in the AppDelegate executes that code path.
func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) {
myManager.sharedInstance.backgroundCompletionHandler = completionHandler
}
I've confirmed that the following change to expose the instance of Alamofire.Manager and access it directly does not produce the warning:
public var manager: Manager
// public var backgroundCompletionHandler: (() -> Void)? {
// get {
// return manager.backgroundCompletionHandler
// }
// set {
// manager.backgroundCompletionHandler = backgroundCompletionHandler
// }
// }
and in the AppDelegate:
func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) {
myManager.sharedInstance.manager.backgroundCompletionHandler = completionHandler
}
Based on this it appears that using a computed property to proxy the completion handler is the cause of the issue.
I'd really prefer not to expose this property and would love to know of any workarounds or alternatives.
It appears as though everything you are doing is correct. I have an example app that does exactly what you've described that works correctly and does not throw the warning you are seeing. I'm guessing you still have some small error somewhere. Here are a few ideas to try out:
Verify the identifier matches the identifier of your background session
Add a didSet log statement on the backgroundSessionHandler in the Manager class temporarily to verify it is getting set
Add a log statement into the sessionDidFinishEventsForBackgroundURLSession to verify it is getting called as expected
Override the sessionDidFinishEventsForBackgroundURLSession on the delegate and manually call the backgroundSessionHandler
Verify you have your Xcode project set up correctly for background sessions
Update 2
Your computed property is wrong. Instead it needs to set the backgroundCompletionHandler to newValue. Otherwise you are never setting it to the new value correctly. See this thread for more info.

How to get a path out of an NSSavePanel object in Swift

I have been attempting to use the NSSavePanel to save text files in a program written in Swift. The only issue is that every time I attempt to use the URL attribute, it has a nil value. Yes, I have a folder selected and a file name in the input when testing. Here's my code:
let saveDialog = NSSavePanel();
saveDialog.beginWithCompletionHandler() { (result: Int) -> Void in
if result == NSFileHandlingPanelOKButton {
let file = NSFileHandle(forWritingToURL: saveDialog.URL!, error: nil)!;
for match in Globals.matches {
if let data = (match.toString() as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
file.writeData(data);
}
}
}
}
// other setup code not shown
When I run this, I always get the Swift equivalent of a null-pointer exception on the
let file = NSFileHandle(forWritingToURL: saveDialog.URL!, error: nil)!;
line. Can I please have some help? What am I doing wrong?
Check the documentation for NSFileHandle(forWritingToURL:error:), it says:
The initialized file handle object or nil if no file exists at url.
So this only works if the file already exists. Which is probably not what you want.
It looks like NSFileHandle cannot create new files at all, so I would just use the following before you try to open the file:
NSFileManager.defaultManager()
.createFileAtPath(saveDialog.URL.path, contents: NSData(), attributes: nil)
Which will create an empty file, which you can then open and write your data to.

Resources