HKWorkoutSessionDelagate protocol conformity - xcode

I'm upgrading a watchOS2 to watchOS3 with xCode 8.0 Beta And I'm having trouble with HKWorkoutSessionDelagate. See image.
The fix-it suggestion, crashes xcode - anyone having similar issues or can anyone point me in the direction of the resolution - that would be much appreciated.
Thanks

Just added this delegate, I didn't get any error. Using Xcode 8.0, Swift 3.0.
//
// InterfaceController.swift
// asf WatchKit Extension
//
// Created by Alvin Varghese on 27/06/16.
// Copyright © 2016 Swift Coder. All rights reserved.
//
import WatchKit
import Foundation
import HealthKit
extension InterfaceController : HKWorkoutSessionDelegate
{
func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date)
{
}
func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: NSError){
}
}
class InterfaceController: WKInterfaceController {
override func awake(withContext context: AnyObject?) {
super.awake(withContext: context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}

Related

Xcode swift preview fails with 'Unknown preview provider "<classname>_"'

There are a few similar questions here, but no answers resolve the issue for me.
My project doesn't start with a number.
It is essentially just this:
import Foundation
import UIKit
class DetailsView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupBackgroud()
setupViews()
}
func setupBackgroud() {}
func setupViews() {}
}
#if DEBUG
import SwiftUI
#available(iOS 13, *)
struct DetailsViewPreview: PreviewProvider {
static var previews: some View {
// view controller using programmatic UI
DetailsView().showPreview()
}
}
#endif
and I get the error:
I have no idea what the 'mangled name' is.
The stupidest fix possible for this error.
I removed the compiler pre-proccessor statements.
Just remove #if DEBUG and #endif.
"It Just Works" 🤦‍♂️

How can I prevent a user from saving a document in SwiftUI?

I'm building a document-based app with SwiftUI on MacOS Big Sur. I want to prevent users from saving the files as it is intended only as a viewer. How can I do this in SwiftUI?
I'm forced to implement the writing method due to the protocol FileDocument
import SwiftUI
struct MyDoc: FileDocument {
static var readableContentTypes: [UTType]
init(configuration: ReadConfiguration) throws {
<#code#> // reading
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
<#code#> // writing
}
}
My app looks something like this
import SwiftUI
#main
struct MyDocApp: App {
var body: some Scene {
DocumentGroup(viewing: MyDoc.self) { file in
ContentView(document: file.$document)
}
}
}
I've already selected 'Read Only' in 'Signing and Capabilities'
I'm not sure how else to prevent this in SwiftUI.
Cmd+S triggers the save behaviour and the menu options are still included.
Here's a sample project demonstrating the issue - Sample Project
I guess one option is to throw an error in the write method and handle it telling the user they aren't allowed to save files. But this seems a bit... hacky!
Can anyone help?
I couldn't find a way either, and ended up doing the-hacky-way:
struct MyDoc: FileDocument {
...
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
throw CocoaError(.fileWriteNoPermission)
}
}
At least it's readable

Thread 1: signal SIGABRT from web view when accessing external link

I am currently trying to deploy a responsive website on mobile devices (iPhone & iPad) via a WebView.
Here are some details regarding the app :
the application's only purpose is to display the webView containing the website
using the WKWebView component since UIWebView is deprecated in my environment
any external links should load a new page within the webView
currently using Swift 3 and Xcode 9.2
made an Outlet between the WebKit WebView and the ViewController
edited the info.plist ; App Transport Security Setting > set NSAllowArbitraryLoads to true
source code :
ViewController.swift
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
// edit the url the app should load here
private var domain = "https://example.com/"
#IBOutlet weak var webView: WKWebView!
override func loadView() {
//delegates the navigation of other urls while still inside the webview
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
webView.allowsLinkPreview = false
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// calls the website in a 'iframe' style
let url = URL(string: domain)
let request = URLRequest(url: url!)
webView.load(request)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: #escaping ((WKNavigationActionPolicy) -> Void)) {
// outputs are for debugging purpose
print("webView :\(webView)" + "\n")
print("decidePolicyForNavigationAction :\(navigationAction)" + "\n")
print("decisionHandler :\(decisionHandler)" + "\n")
switch navigationAction.navigationType {
case .linkActivated:
print("request : " + navigationAction.request.url!.absoluteString)
self.webView?.load(navigationAction.request)
return
default:
break
}
if let url = navigationAction.request.url {
print("url : " + url.absoluteString)
}
decisionHandler(.allow)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
AppDelegate.swift :
import UIKit
import WebKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
}
My trouble comes when trying to open external and internal links ; the app will throw a signal SIGABRT.
From what I understand, this error usually happens when there is an Outlet mismatch, but my project has only a single Outlet (WebView / ViewController). I tried deleting it and re-creating it to no avail.
If the issue is that no Outlet are made between the page loaded from an external link and my app I fail to see how to solve this since I have no control over the website.
Note : when I set webView.allowsLinkPreview to true (in func loadView()), the app loads the new page but takes a considerable amount of time. Also the function webView isn't called a second time when this happens.
Any help will be much appreciated.
Thank you.
Edit. as requested in a comment, here is what the debugger throws :
libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)
Also, the Thread 1 SIGABRT signal appears to be in the AppDelegate class.
The interesting error message should be
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Completion handler passed to -[myAppName webView:decidePolicyForNavigationAction:decisionHandler:] was not called'
In webView(_ webView:, decidePolicyFor navigationAction:, decisionHandler:) in one particular case you don't do decisionHandler(someValue), that's why it crashes.
So in
case .linkActivated:
print("request : " + navigationAction.request.url!.absoluteString)
self.webView?.load(navigationAction.request)
return
You need to do decisionHandler(someValue) before you do the return.

Check if iOS10 or lower during compile time

I am implementing new notifications, with UNUserNotificationCenter. But I need to keep it backwards compatible, therefore I have checks all over the place:
if #available(iOS 10.0, *) { ... }
else { ... }
Which seems to work fine in iOS10. To be able to use the UNUserNotificationCenter framework, I have to import:
import NotificationCenter
But it crashes the iOS9.3, because it does not know what it is.
It is a compile time action, not a runtime action - so it means I can not put condition on the imports.If I create a separate class, and put
#available(iOS 10.0, *)
class ....
there the imports are also happening before the class implementation.
How should I work around this issue?
Try navigating to Build Phases->Link Binary with Libraries and add NotificationCenter and set the status to "optional" rather than "required".
first of all you must use:
import UserNotifications
for local notifications.
conditions: Xcode 8 beta 6 and Sierra beta6
some test code:
a) iOS 10 only for swift 3:
override func viewDidLoad() {
super.viewDidLoad()
// ADC site:
// Listing 1
// Requesting authorization for user interactions
/* let center = UNUserNotificationCenter.currentNotificationCenter()
center.requestAuthorizationWithOptions([.Alert, .Sound]) { (granted, error) in
}
*/
// swift 3.0:
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
2) support iOS 9: (I have changed deployment target)
// swift 3.0:
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
} else {
// Fallback on earlier versions
}

Trying to save variable as list of custom parse object (UserRecipe) and print them to the xcode console

I'm trying to do just a real simple thing in xcode with the ios parse sdk (1.9.1). Im trying to create a variable that will store all the data I have in my parse custom object called UserRecipe
Here is what my parse set up looks like
Below is my code:
import UIKit
import Parse
//import ParseFacebookUtilsV4
import FBSDKCoreKit
import FBSDKLoginKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let userRecipe = PFObject(className: "UserRecipe")
print(userRecipe)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
In my xcode console log this is what I have being returned:
It doesnt seem to be returning my 5 recipe objects in the UserRecipe class in parse. can anyone help me out with this? Thanks in advance for any assistance
The posted code just creates a new object locally and logs it to the console. In order to see the objects stored in the remote data, you'll need to query them.
Read all about it here, but to summarize...
var query = PFQuery(className:"UserRecipe")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects {
for object in objects {
print(object["recipeName"])
}
}
} else {
print("Error: \(error!) \(error!.userInfo)")
}
}

Resources