I am trying to make a basic script that will pull my daily steps from HealthKit on iOS, however when the page is triggered - nothing happens. It should request permission to read HealthKit data and I can't work out where I'm going wrong.
Here's my code:
import Foundation
import UIKit
import HealthKit
class HealthKitPage: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
class HealthKitManager {
let HealthStore = HKHealthStore()
func AuthoriseHealthKit() -> Bool {
var isEnabled = true
if HKHealthStore.isHealthDataAvailable() {
let StepCount = NSSet(object: HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount))
let DataTypesToWrite = NSSet(object: StepCount)
let DataTypesToRead = NSSet(object: StepCount)
HealthStore.requestAuthorization(toShare: nil, read: (StepCount as! Set<HKObjectType>)) {
(success, error) -> Void in
isEnabled = success
}
}else{
isEnabled = false
}
return isEnabled
}
}
Can anyone offer any suggestions?
I was able to resolve this using Himali's answer, but it needed converting to Swift 3, here's my working file:
import Foundation
import UIKit
import HealthKit
import UIKit
import HealthKit
class HealthKitPage : UIViewController
{
let healthStore: HKHealthStore = HKHealthStore()
override func viewDidLoad()
{
var shareTypes = Set<HKSampleType>()
shareTypes.insert(HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!)
var readTypes = Set<HKObjectType>()
readTypes.insert(HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!)
healthStore.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) -> Void in
if success {
print("success")
} else {
print("failure")
}
if let error = error { print(error) }
}
}
import UIKit
import HealthKit
class HealthKitPage : UIViewController
{
let healthStore: HKHealthStore = HKHealthStore()
override func viewDidLoad()
{
var shareTypes = Set<HKSampleType>()
shareTypes.insert(HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!)
var readTypes = Set<HKObjectType>()
readTypes.insert(HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!)
healthStore.requestAuthorizationToShareTypes(shareTypes, readTypes: readTypes) { (success, error) -> Void in
if success {
print("success")
} else {
print("failure")
}
if let error = error { print(error) }
}
}
}
Related
Below is my main view controller. The user selects images of clothing which are then categorized using CoreML and given a filename. Then, data is saved to Realm. When I call the function loadClothing(), the array is empty even though items were added during func detect. Any help is much appreciated!
import UIKit
import PhotosUI
import RealmSwift
import CoreML
import Vision
class ViewController: UIViewController, PHPickerViewControllerDelegate {
#IBOutlet weak var shoesImageView: UIImageView!
#IBOutlet weak var shirtImageView: UIImageView!
#IBOutlet weak var pantsImageView: UIImageView!
var documentsUrl: URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
let realm = try! Realm()
var clothing: Results<Clothing>?
override func viewDidLoad() {
super.viewDidLoad()
loadClothing()
let clothingArray = Clothing()
print(clothingArray)
}
#IBAction func addClothesButton(_ sender: UIBarButtonItem) {
pickPhotos()
}
#IBAction func randomizeButton(_ sender: UIBarButtonItem) {
loadClothing()
let clothingArray = Clothing()
print(clothingArray)
shirtImageView.image = load(fileName: clothingArray.shirtImages.randomElement()!)
pantsImageView.image = load(fileName: clothingArray.pantsImages.randomElement()!)
shoesImageView.image = load(fileName: clothingArray.shoesImages.randomElement()!)
}
//MARK: - PHPickerViewController
#objc func pickPhotos() {
var config = PHPickerConfiguration()
config.selectionLimit = 25
config.filter = PHPickerFilter.images
let pickerViewController = PHPickerViewController(configuration: config)
pickerViewController.delegate = self
self.present(pickerViewController, animated: true, completion: nil)
}
// MARK: - PHPickerViewControllerDelegate
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true, completion: nil)
for result in results {
result.itemProvider.loadObject(ofClass: UIImage.self) {(object, error) in
if let image = object as? UIImage {
DispatchQueue.main.async {
guard let fileName = result.itemProvider.suggestedName else {
fatalError("Could not retrieve file name.")
}
print(fileName)
guard let ciImage = CIImage(image: image) else {
fatalError("Could not convert to CI Image.")
}
self.detect(image: ciImage, fileName: fileName)
}
}
}
}
}
// MARK: - Core ML
func detect(image: CIImage, fileName: String) {
guard let model = try? VNCoreMLModel(for: ClothingClassifier(configuration: MLModelConfiguration()).model) else {
fatalError("Loading CoreML Model failed.")
}
let request = VNCoreMLRequest(model: model) { (request, error) in
guard let results = request.results as? [VNClassificationObservation] else {
fatalError("Model failed to process image.")
}
let newClothing = Clothing()
if let firstResult = results.first {
let uiImage = UIImage(ciImage: image)
if firstResult.identifier.contains("shirts") {
newClothing.shirtImages.append(fileName)
} else if firstResult.identifier.contains("pants"){
newClothing.pantsImages.append(fileName)
} else if firstResult.identifier.contains("shoes") {
newClothing.shoesImages.append(fileName)
}
self.save(clothing: newClothing)
print(newClothing)
}
}
let handler = VNImageRequestHandler(ciImage: image)
do {
try handler.perform([request])
}
catch {
print(error)
}
}
// MARK: - Data Manipulation Methods
func save(clothing: Clothing) {
do {
try realm.write {
realm.add(clothing)
}
} catch {
print("Error saving uploaded clothing. \(error)")
}
}
func loadClothing() {
clothing = realm.objects(Clothing.self)
print("loaded")
}
private func load(fileName: String) -> UIImage? {
let fileURL = documentsUrl.appendingPathComponent(fileName)
do {
let imageData = try Data(contentsOf: fileURL)
return UIImage(data: imageData)
} catch {
print("Error loading image : \(error)")
}
return nil
}
}
Clothing Class
import Foundation
import RealmSwift
class Clothing: Object {
let shirtImages = List<String>()
let pantsImages = List<String>()
let shoesImages = List<String>()
}
I am still quite new to iOS development and I am trying to teach myself good coding practices and design patterns in Swift starting with MVVM. I need to pass the data from a completion handle in my ServiceCall class to my ViewModel. I would like assistance in understanding how I can do it and also guidance in best practices using MVVM on my code.
This is what I have done so far:
Model
struct Login {
var appVersion: String ?
var deviceID : String ?
var deviceOS : String ?
var password : String ?
var username : String ?
}
Service Call / API Client
class LoginServiceCall : NSObject, URLSessionDelegate {
let viewResponse = ThrowResponse()
func requestLogin(request: URLRequest, requestObject: Login, completion: #escaping ([NSDictionary] ? ) -> Void) {
let searchParams = Login.init(appVersion: requestObject.appVersion, deviceID: requestObject.deviceID, deviceOS: requestObject.deviceOS, password: requestObject.password, username: requestObject.username)
var request = request
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: searchParams, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: {
data, response, error -> Void in
do {
let json = try JSONSerialization.jsonObject(with: data!) as ? Dictionary<String, Any>
//completion(json!)
// This is where i would like to pass the dictionary data
} catch {
DispatchQueue.main.async {
self.viewResponse.dismissLoader()
self.viewResponse.showFailureAlert(title: "Failure", message: "")
completion(nil)
}
}
})
task.resume()
}
}
View Controller
class LoginViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var loginButton: UIButton!
#IBOutlet var usernameOrEmailTextField: UITextField ?
#IBOutlet var passwordTextField : UITextField ?
var serviceBalance = 0.0
let defaults = UserDefaults.standard
var Reach : Reachability ? = Reachability()
var viewModel : LoginViewModel ?
override func viewDidLoad() {
super.viewDidLoad()
usernameOrEmailTextField?.delegate = self
passwordTextField?.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
usernameOrEmailTextField?.resignFirstResponder()
passwordTextField?.resignFirstResponder()
return (true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func loginButton(_ sender: Any) {
viewModel?.setLoginObject(withUsername: usernameOrEmailTextField?.text, withPassword : passwordTextField?.text)
}
#IBAction func forgotPasswordButton(_ sender: Any) {
self.performSegue(withIdentifier: "forgotPasswordSegue", sender: nil)
}
#IBAction func registerButton(_ sender: Any) {
self.performSegue(withIdentifier: "registerUserSegue", sender: nil)
}
}
ViewModel
class LoginViewModel: NSObject {
var Reach: Reachability? = Reachability()
var login: Login?
var homeViewDictionary: [NSDictionary]?
var APIClient: LoginServiceCall!
var request = URLRequest(url: URL(string: "http://myapiuser/login")!)
func setLoginObject(withUsername username: String?, withPassword password: String?){
login?.username = username
login?.password = password
login?.appVersion = self.getAppVersion()
login?.deviceID = self.getDeviceID()
login?.deviceOS = self.getDeviceOs()
APIClient.requestLogin(request: request, requestObject: login! { (AppDictionary) in
DispatchQueue.main.async {
self.homeViewDictionary = AppDictionary
}
}, completion: ())
}
func getAppVersion() -> String { return "0.2" }
func getDeviceID() -> String {
if let deviceid = UIDevice.current.identifierForVendor?.uuidString { return deviceid }
}
func getDeviceOs() -> String {
let systemVersion = UIDevice.current.systemVersion
let model = UIDevice.current.model
return systemVersion+" "+model
}
}
I am building a simple app that talks to a web service.
I have used the delegates method to communicate data (from my model to view controller).
But I am not sure how to read the data from view controller (text_field.text) in my model. I need to do that so that I can pass the right parameter to my webservice
my view controller is:
import UIKit
class ViewController: UIViewController,HomeModelDelegate {
var homeModel = HomeModel()
#IBOutlet weak var loginid: UITextField!
#IBOutlet weak var pwd: UITextField!
#IBAction func submit(_ sender: UIButton) {
homeModel.chkpwd()
//Here viewcontroller is assigning itself to the homemodel's delegate property
homeModel.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
loginid.layer.cornerRadius=10
pwd.layer.cornerRadius = 10
}
func itemsDownloaded(locations: [Location]) {
loginid.text = locations[0].pwd
}
}
My model code is:
import UIKit
protocol HomeModelDelegate{
func itemsDownloaded(locations:[Location])
}
class HomeModel: NSObject
{
var delegate:HomeModelDelegate?
func chkpwd()
{
//Hit the webservice url
let x = ViewController()
let z = x.loginid
let serviceUrl = "http://www.xyz.in/webservice.php?loginid=(loginid.text)"
//download the json data
let url = URL(string: serviceUrl)
if let url = url {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url, completionHandler:
{ (data, response, error) in
if error == nil {
//succeeded
self.parseJson(data!)
}
else {
//failed
}
})
task.resume()
}
}
func parseJson(_ data:Data){
var locArray = [Location]()
do{
let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
for jsonResult in jsonArray{
let jsonDict = jsonResult as! [String:String]
let loc = Location(pwd: jsonDict["loginid"]!, loginid: jsonDict["pwd"]!)
locArray.append(loc)
//pass the location back to the delegate
delegate?.itemsDownloaded(locations: locArray)
}
}
catch{
print("An error occured")
}
}
}
Please try this :
import UIKit
class ViewController: UIViewController,HomeModelDelegate {
var homeModel = HomeModel()
#IBOutlet weak var loginid: UITextField!
#IBOutlet weak var pwd: UITextField!
#IBAction func submit(_ sender: UIButton) {
homeModel.z = loginid.text! // ASSIGNING z here
homeModel.chkpwd()
//Here viewcontroller is assigning itself to the homemodel's delegate property
homeModel.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
loginid.layer.cornerRadius=10
pwd.layer.cornerRadius = 10
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func itemsDownloaded(locations: [Location]) {
loginid.text = locations[0].pwd
}
}
Model :
import UIKit
protocol HomeModelDelegate{
func itemsDownloaded(locations:[Location])
}
class HomeModel: NSObject
{
var z:String = "" // INITIALIZING z
var delegate:HomeModelDelegate?
func chkpwd()
{
print(z) // CALLING z
//Hit the webservice url
let serviceUrl = "http://www.xyz.in/webservice.php?loginid=(loginid.text)"
//download the json data
let url = URL(string: serviceUrl)
if let url = url {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url, completionHandler:
{ (data, response, error) in
if error == nil {
//succeeded
self.parseJson(data!)
} else {
//failed
}
})
task.resume()
}
}
func parseJson(_ data:Data){
var locArray = [Location]()
do{
let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
for jsonResult in jsonArray{
let jsonDict = jsonResult as! [String:String]
let loc = Location(pwd: jsonDict["loginid"]!, loginid: jsonDict["pwd"]!)
locArray.append(loc)
//pass the location back to the delegate
delegate?.itemsDownloaded(locations: locArray)
}
} catch {
print("An error occured")
}
}
}
How can I solve the leak that happened in the sample code below, as seen in this image:
import UIKit
import Alamofire
import AlamofireObjectMapper
class ViewController: UIViewController {
#IBAction func action(_ sender: Any) {
load { (posts: [Post]) in
posts.map({ (post: Post) -> Void in
print(post.title)
})
}
}
func load( posts: (([Post]) -> Void)!) {
let urlString = "https://jsonplaceholder.typicode.com/posts"
let url = try! urlString.asURL()
Alamofire.request(url).validate().responseArray { (response: DataResponse<[Post]>) in
guard let postArray = response.result.value else {return}
posts(postArray)
}
}
}
The following simple class doesn't play a video URL. What I get is a black empty screen. Why?
import Foundation
import AVKit
import AVFoundation
class EditShowVideoViewController:AVPlayerViewController {
override func viewDidLoad() {
var error: NSError?
if let urlString = gBlissMedium!.mediumURL {
let url = NSURL(string: urlString)
player = AVPlayer(URL:url)
}
}
override func viewDidAppear(animated: Bool) {
player.play()
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
(lldb) po urlString
"http://files.parsetfss.com/6b8388b7-14c6-431a-a795-2b33f9d47081/tfss-56cf2c67-111c-4724-8e63-3755fe1b85f7-hst_1.mpg"
if let urlString = gBlissMedium!.mediumURL {
let url = NSURL(string: urlString)
player = AVPlayer(URL:url)
}
here player is being defined locally in viewDidLoad, it should be an instance variable of the class