#StackBounty: #ios #swift #uitableview #slider access stored values from a tableViewCell and save them to firebaseDatabase

Bounty: 50

I have a tableViewCell that has a range slider inside of it. I would like the values from the range slider to be saved to firebase when the user hits handleSave(). I can print out the values when the user slides the range slider inside the tableViewCell, but I cannot save this value from the tableViewCell itself nor can I print the values from the tableViewVC. When I try to print the values from the tableViewVC I don’t see anything in my console. But If I were to print them from my tableViewCell itself then it works just fine.

The code that I am using to try and print the values from my tableViewVC is,

  let costRangeCell = AgeRangeCell(style: .default, reuseIdentifier: nil)
        
        costRangeCell.rangeSlider.minimumValue = 5
        costRangeCell.rangeSlider.maximumValue = 200
        costRangeCell.rangeSlider.lowValue = 5
        costRangeCell.rangeSlider.highValue = 200
        costRangeCell.rangeSlider.minimumDistance = 20
        print(costRangeCell.lowLabel.text)
        print(costRangeCell.highLabel.text)

rangeSlider.valuesChangedHandler = { [weak self] in
        guard let `self` = self else {
            return
        }
        let lowCenterInSlider = CGPoint(x:self.rangeSlider.lowCenter.x, y: self.rangeSlider.lowCenter.y - 30)
        let highCenterInSlider = CGPoint(x:self.rangeSlider.highCenter.x, y: self.rangeSlider.highCenter.y - 30)
        let lowCenterInView = self.rangeSlider.convert(lowCenterInSlider, to: self.contentView)
        let highCenterInView = self.rangeSlider.convert(highCenterInSlider, to: self.contentView)
        
        self.lowLabel.center = lowCenterInView
        self.highLabel.center = highCenterInView
        self.lowLabel.text = String(format: "%.1f", self.rangeSlider.lowValue)
        self.highLabel.text = String(format: "%.1f", self.rangeSlider.highValue)
        print(costRangeCell.rangeSlider.lowValue)
        print(costRangeCell.rangeSlider.highValue)

        return costRangeCell

  }

in the above print statements, I can see the value of the range slider that the user has chosen.

and how I plan to save the data is in the tableViewVc as well.

    @objc fileprivate func handleSave() {
    let costRangeCell = AgeRangeCell(style: .default, reuseIdentifier: nil)
    guard let uid = Auth.auth().currentUser?.uid else { return }
    let docData: [String: Any] = [
        "info": info,
        "info": info,
        "info": info,
        "info": info,
        "info": info,
        "info": info,
        "minSeekingCost": costRangeCell.rangeSlider.minimumValue.self,
        "maxSeekingCost": costRangeCell.rangeSlider.maximumValue.self
        
    ]
    
    self.updateUserDataIntoDatabseWithUID(uid: uid, values: docData as [String : AnyObject])
    print("Finished saving user info")
    self.dismiss(animated: true, completion: {
        print("Dismissal complete")
        print(costRangeCell.rangeSlider.lowValue)
        print(costRangeCell.rangeSlider.highValue)
    })
}

when I try to see what the value is being printed here, it just shows 0 and 1 not the actual number of the rangeSlider

and my ageRangeCell is

class AgeRangeCell: UITableViewCell {

let rangeSlider: AORangeSlider = {
    let slider = AORangeSlider()
    slider.minimumValue = 0
    slider.maximumValue = 100
    slider.stepValue = 5
    return slider
}()

var user: User?
let lowLabel = UILabel()
let highLabel = UILabel()

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    commonInit()
}
required init?(coder: NSCoder) {
    super.init(coder: coder)
    commonInit()
}
func commonInit() -> Void {
    
    lowLabel.textAlignment = .center
    lowLabel.frame = CGRect(x:0, y:0, width: 60, height: 20)
    
    highLabel.textAlignment = .center
    highLabel.frame = CGRect(x: 0, y: 0, width: 60, height: 20)
    
    [rangeSlider, lowLabel, highLabel].forEach {
        contentView.addSubview($0)
    }
    
    rangeSlider.translatesAutoresizingMaskIntoConstraints = false
    let g = contentView.layoutMarginsGuide
    NSLayoutConstraint.activate([
        rangeSlider.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
        rangeSlider.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
        rangeSlider.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
        rangeSlider.heightAnchor.constraint(equalToConstant: 40.0),
    ])

    let c = rangeSlider.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0)
    c.priority = UILayoutPriority(rawValue: 999)
    c.isActive = true



    }
    
}
}

When the print statement is inside of the ageRangeCell, I can successfully print the values of the range slider. But when I try to print the rangeSliders value inside of the tableViewVC it is not working. The only way for me to save this information to firebase is if I had access to its value. What am I missing? If I can print the statements inside of the tableViewVC I can then save them to the database.


Get this bounty!!!

#StackBounty: #ios #swift #ios14 #phasset phResourceManager.writeData(for… wont run on iOS 14

Bounty: 50

Before I updated to iOS 14 on my iPhone, this code was working perfectly. After, iOS 14 this is weirdly not running… it is very odd and I have not seen any solution online, additionally from my investigation, I have not been able to see any change.

This code is used in order to retrieve a videoURL for this video from the imported Camera Roll (I use import Photos…).

phResourceManager.writeData(for: resource.last!, toFile: newURL!, options: resourceRequestOptions) { (error) in
    if error != nil {
        print(error, "not c67omplted error?")
    } else {
        print("woah completedd 345?")
        
        newUserTakenVideo.videoURL = newURL
        print(newUserTakenVideo.videoURL, "<--?")
    }
}

EDIT:
To be clear, it "does not run" means the compleition block never runs… as in it never even runs and gives an error, the compleition block simply never is called (nothing prints at least..)

And here is a print statement printing out all the values I pass in to the parameters:

phResourceManager:
<PHAssetResourceManager: 0x282d352c0>

resource.last:

Optional(<PHAssetResource: 0x28128bc00> {
    type: video
    uti: public.mpeg-4
    filename: v07044090000bu6n1nhlp4leque7r720.mp4
    asset: C97B45D3-7039-4626-BA3E-BCA67912A2A9/L0/001
    locallyAvailable: YES
    fileURL: file:///var/mobile/Media/DCIM/113APPLE/IMG_3404.MP4
    width: 576
    height: 1024
    fileSize: 4664955
    analysisType: unavailable
    cplResourceType: Original
    isCurrent: YES
}) 

newURL:
Optional(file:///var/mobile/Containers/Data/Application/E2792F47-142E-4601-8D5B-F549D03C9AFE/Documents/Untitled%2027228354.MP4)

resourceRequestOptions:
<PHAssetResourceRequestOptions: 0x28230d480>

Note: this is the decleration for the resource variable:

let resource = PHAssetResource.assetResources(for: (cell?.assetPH)!)


Get this bounty!!!

#StackBounty: #swift #xcode #xcode12 Xcode: "<unknown>:0: error: cannot load module 'main' as 'Swift'" …

Bounty: 50

Just started using Swift on Xcode.

For some reason, anytime I want to compile, it shows the error: <unknown>:0: error: cannot load module 'main' as 'Swift'

The only way I could find to fix it is to either clean build folder or delete build folder myself, then compile.

The code I have is just changing from:

print("Hello, world!")

to

print("Hello, world")

Am I doing something totally wrong?

Xcode version: 12.1 (12A7403) with Xcode 12.1 Toolchain


Get this bounty!!!

#StackBounty: #ios #swift #frameworks Swift library that supports both app and extension

Bounty: 250

I’ve created a library for my iOS app but I get the warning linking against a dylib which is not safe for use in application extensions.

I know this is because I haven’t enabled Allow app extension API only for my library. So when I enable that setting my library gives errors where I have used UIApplication.shared.

I know I cannot use shared in my extension, and don’t actually need to, but this library is used by both my app and my extension.

So the question is, how can I compile the library with a guard around UIApplication.shared?

I already use this:

#if !IS_EXTENSION
    // Cancel the background task
    UIApplication.shared.endBackgroundTask(bgTask)
#endif

and set IS_EXTENSION for Active Compilation Conditions in my extension target, and also IS_EXTENSION=1 for Preprocessor Macros in my app extension, however the library still gives me warnings on these lines.


Get this bounty!!!

#StackBounty: #swift #http #post http Post says its working but it isn't posting on localhost

Bounty: 100

I’ve been trying to do an HTTP post to my localhost using swift for a mobile app, it prints Result -> Optional(["user": larry]) which should mean it works but it isn’t posting anything on my localhost. My code is:

func ReqUsers() -> Void {

        let json = ["user":"larry"]

        do {

            let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)

            let url = NSURL(string: "http://192.168.1.318:8080")! /*localhost*/
            let request = NSMutableURLRequest(url: url as URL)
            request.httpMethod = "POST"

            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            request.httpBody = jsonData

            let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
                if error != nil{
                    print("Error -> (String(describing: error))")
                    return
                }
                do {
                    let result = try JSONSerialization.jsonObject(with: /*data!*/ request.httpBody!, options: .allowFragments) as? [String:AnyObject]
                    print("Result -> (String(describing: result))")
                    
                } catch {
                    print(response!)
                    print("Error -> (error)")
                    print("that")
                }
            }

            task.resume()
        } catch {
            print(error)
            print("this")
        }
        print("called")
    }

thanks for your time

for more info on the backend it’s being written with goLang and here is the code:

package main

import (
    "fmt"
    //"os"
    //"io/ioutil"
    //"log"
    "net/http"
)


func main() {
    http.HandleFunc("/", HelloServer)
    http.ListenAndServe(":8080", nil)
   
}

func HelloServer(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello")
}


Get this bounty!!!

#StackBounty: #swift #video #ios14 Portrait videos no longer retain aspect ratio in iOS 14

Bounty: 300

Using version Texture 3.0.0 with XCode 12 and iOS 14, a problem that appears only on iOS 14 devices, is that portrait videos load with the wrong resolution (it may seem that they swap their width with their height).

Auto play works fine, but manual play does not.
Portrait videos are broken, but landscape videos are not.
The issue is that the gravity applied seems to stretch the video using the wrong width/height for portrait videos.

Sample app below (using a public portrait video I uploaded):

//
//  ViewController.swift
//  test video
//
//  Created by Ericos Georgiades on 22/09/2020.
//

import UIKit
import AVFoundation
import AsyncDisplayKit

class ViewController: UIViewController {

    
    @IBOutlet weak var videoView: UIView!
    private let videoNode = ASVideoNode();
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        videoNode.gravity = AVLayerVideoGravity.resizeAspectFill.rawValue;
        videoNode.muted = true;
        videoNode.shouldAutorepeat = true;
        videoNode.shouldAutoplay = false; // works if true
        videoView.addSubnode(videoNode);
        videoNode.frame = videoView.frame;
        
        let asset = AVAsset(url: URL(string: "https://storage.googleapis.com/pao-uat-6b24c.appspot.com/users/0QhK2lnaQ49BftJTRQ46/spots/7q0Q2TjiIyHyrNTBbJOO/media/WaMnS8Np5vkTcIV0rGyJ/WaMnS8Np5vkTcIV0rGyJ?alt=media&token=75542345-06cc-4e37-a422-1ff2a1cf47c2")!)
        videoNode.asset = asset

        DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
            self.videoNode.play();
        }
    }
}

I have yet to figure out if this is a bug with the library or if this is possible to resolve in Swift without a library fix (or if its needed at all).

Also posted as a bug on https://github.com/TextureGroup/Texture/issues/1918


Get this bounty!!!

#StackBounty: #ios #swift #uitableview #drag-and-drop #uikit UITableView drag and drop a cell onto another cell?

Bounty: 150

I have a UITableView with a Drag and Drop delegate set up. I am able to drag cells between other cells in the UITableView but it does not seem like there is a delegate method for what happens if I drag a cell on top of another cell, in which case I want to combine the two cells (kind of like dragging around apps in iOS). I couldn’t seem to find a delegate method that is called when a cell is placed on top of another cell. What’s the best way to do detect when a cell has been ‘dropped’ ontop of another cell? Thanks


Get this bounty!!!

#StackBounty: #swift #ios #reactive-programming #rx-swift UIView position updates based on device motion via RxSwift

Bounty: 50

I’ve created a simple function to work as a level, where the dot on screen is centered when the device is completely flat. It changes position based on device orientation. I use RxSwift to update the position of the dot. I’m relatively new to RxSwift, so I’m worried that I’m not using it correctly or to its full value.

I also don’t understand capturing self all that well, so please feel free to analyze that as well.

Any input is appreciated!

class ViewController: UIViewController {

    @IBOutlet var levelDot: UIView!
    var positiveMax: (x: CGFloat, y: CGFloat)!
    
    override func viewDidLoad() {
        levelDot.center = self.view.center
        super.viewDidLoad()
        positiveMax = (view.frame.maxX, view.frame.maxY)
        initGryo()
    }

    fileprivate func initGryo() {
        let pitch = PublishSubject<Double>()
        let roll = PublishSubject<Double>()
        let motion = CMMotionManager()
        guard motion.isDeviceMotionAvailable else { return }
        motion.deviceMotionUpdateInterval = 1/60
        motion.startDeviceMotionUpdates()
        let gyroTimer = Timer(fire: Date(), interval: 1/60, repeats: true, block: { timer in
            if let attitude = motion.deviceMotion?.attitude {
                let yModifier: CGFloat = 1.3 // modifier is to make small changes seem bigger on the screen
                
                _ = pitch.map( { (self.positiveMax!.y + CGFloat($0)*self.positiveMax!.y * yModifier) })
                    .map( {$0 / 2} )
                    .subscribe(onNext: { centerY in
                        
//prevent dot from moving off screen
                        guard centerY < self.positiveMax.y else { 
                            self.levelDot.center.y = self.positiveMax.y
                            return
                        }
                        guard centerY > 0 else {
                            self.levelDot.center.y = 0
                            return
                        }
//dot position -- does this capture self? would making levelDot a weak var prevent this?
                        self.levelDot.center.y = centerY
                        
                    })
                pitch.onNext(attitude.pitch)
                
                let xModifier: CGFloat = 1.15 // modifier is to make small changes seem bigger on the screen
                _ = roll.map( { (self.positiveMax!.x + CGFloat($0)*self.positiveMax!.x*xModifier) })
                    .map({ $0 / 2 })
                    .subscribe(onNext: { centerX in
//prevent dot from moving off screen
                        guard centerX < self.positiveMax.x else {
                            self.levelDot.center.x = self.positiveMax.x
                            return
                        }
                        guard centerX > 0 else {
                            self.levelDot.center.x = 0
                            return
                        }
//dot position 
                        self.levelDot.center.x = centerX
                    })
                roll.onNext(attitude.roll)
            }
        })
        RunLoop.current.add(gyroTimer, forMode: .default)
        
    }
    
}


Get this bounty!!!

#StackBounty: #ios #swift #uicollectionview Incomplete delete animation for a single row horizontal UICollectionView with UICollectionV…

Bounty: 500

Currently, I have a single row horizontal UICollectionView with UICollectionViewCompositionalLayout

[All] [Calendar] [Home2] [Work3] [Work4] ... [Work8] [⚙]

The UICollectionView, is acting as a scrollable Tab layout navigation bar.

When user switch to [⚙] page, he is able to delete the tab before itself. In this case, during the 1st time of the delete operation, tab [Work8] will be removed.

Here’s the straightforward code to achieve so.


https://github.com/yccheok/ios-tutorial/blob/debug/TabDemo/TabDemo/ViewController.swift#L144

func debug() {
    if tabInfos.count < 2 {
        return
    }
    
    let index = tabInfos.count-2
    tabInfos.remove(at: index)
    let indexPath = getIndexPath(index)
    self.tabCollectionView.deleteItems(at: [indexPath])
    
    // TODO: Possible solution.
    /*
    self.tabCollectionView.reloadData()
    DispatchQueue.main.async() {
        let indexPath = self.getIndexPath(self.tabInfos.count-1)
        self.tabCollectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredVertically)
        self.tabCollectionView.scrollToItem(at: indexPath, at: .right, animated: true)
    }
     */

    // Clear left/ right cached view controllers - https://stackoverflow.com/a/21624169/72437
    pageViewController.dataSource = nil
    pageViewController.dataSource = self

    // Don't forget to adjust the selection index.
    if index < self.selectedTabInfoIndex {
        selectedTabInfoIndex -= 1
    }
}

Strange outcome

https://www.youtube.com/watch?v=Wzgb4QErUes (Please refer to this video for complete deletion animation)

This is how it looks like before deletion

enter image description here

As you can see in the video, after the deletion of [Work8], the left side tab ([Work3]) is not visible

enter image description here

My expected outcome is, [Work3] should be visible too immediately, without any additional action from user. I need to tap on the UICollectionView, move it abit, only all the tabs will appear

enter image description here


I prefer not to use reloadData, as

  1. It will not preserve scroll position of UICollectionView.
  2. It does not have animation.

Do you have any idea what is the root cause of this strange animation outcome?

Here’s the complete source code to try it out – https://github.com/yccheok/ios-tutorial/releases/tag/debug


Get this bounty!!!

#StackBounty: #ios #swift #xcode #audio #audio-recording How to record audio with a certain threshold filter in swift

Bounty: 50

enter image description here

I need to add this functionality in one of my app in swift, I want the user to adjust the threshold and so it’ll be only recorded when it crosses the limit set by the user and stop automatically or in a given time when the user stops.

It would be great if you can share your expertise in how to collect all the data in one file like when a user will pause and continue it’ll keep all the audio in one file.

I actually have no idea about this and will truly appreciate any kind of feedback.

Thanks.


Get this bounty!!!