how to change url when button is pressed in swift - swift

I'm having 2 buttons button1 & button2
when button1 is pressed I have to get url1 and when button2 is pressed get url2 in the below function
func fetchXMLData() {
XMLParserFactory.fetchData(url: "https://brwterrgn.ergwgw.com/etwtt.cms") { (listOfXMLVM, error) in
print("Fetch xml data")
if error == nil {
self.listOfNewsVM = listOfXMLVM!
self.tableView.reloadData()
}
else {
print(error?.localizedDescription ?? "Error")
}
}
}
}

Add parameter to this fetchXMLData function
func fetchXMLData(withUrl url: String)
also replace your url by this url variable
XMLParserFactory.fetchData(url: url)
Now in every IBAction call this function with different url passed as parameter of this method
#IBAction func button1pressed(_ sender: UIButton) {
fetchXMLData(withUrl: "url1.com")
}
#IBAction func button2pressed(_ sender: UIButton) {
fetchXMLData(withUrl: "url2.com")
}

You can try to make the url a parameter and change it from the caller place
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
fetchXMLData(url: "https://value.com/etwtt.cms")
}
func buttonAct(_ sender: UIButton) {
fetchXMLData(url: "https://brwterrgn.ergwgw.com/etwtt.cms")
}
func fetchXMLData(url:String) {
XMLParserFactory.fetchData(url:url) { (listOfXMLVM, error) in
print("Fetch xml data")
if error == nil {
self.listOfNewsVM = listOfXMLVM!
self.tableView.reloadData()
}
else {
print(error?.localizedDescription ?? "Error")
}
}
}
Edit
class FirstVC: UIViewController {
func showSecond(_ sender: UIButton) {
let sec = //
sec.delegate = self
present/push(sec)
}
func fetchXMLData(url:String) {
XMLParserFactory.fetchData(url:url) { (listOfXMLVM, error) in
print("Fetch xml data")
if error == nil {
self.listOfNewsVM = listOfXMLVM!
self.tableView.reloadData()
}
else {
print(error?.localizedDescription ?? "Error")
}
}
}
class SecondVC: UIViewController {
weak var delegate:FirstVC?
func buttonAct(_ sender: UIButton) {
delegate?.fetchXMLData(url: "https://brwterrgn.ergwgw.com/etwtt.cms")
}
}

Related

After passing Object to another ViewController the object becomes nil, Swift?

I am passing a Venue object from the PreferencesVC to DiscoverVC by declaring an instance of the class and setting the venue variable to the object being passed.
By the time the code executes beginLoadView() the Venue object is nil and therefore the if statement incorrectly executes
Console output:
Class PreferencesVC: UIViewController{
#IBAction func doneBtnTapped(_ sender: Any) {
print("inside doneBtnTapped selectedVenue.name: \(selectedVenue?.name ?? "selectedVenue is nil")")
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
discoverVC.venue = self.selectedVenue!
DataService.run.updateUserDiscoveryPreferences(forUID: Auth.auth().currentUser!.uid, discoverableBool: discoverable!, preferences: preferences) { (success) in
self.dismissDetail()
}
}//end func
}
Class DiscoverVC: UIViewController{
var venue: Venue?{
didSet{
print("DiscoverVC venue name: \(venue?.name ?? "venue name")")
}
}
override func viewWillDisappear(_ animated: Bool) {
print("inside viewWillDisappear")
venue = nil
}//end func
override func viewWillAppear(_ animated: Bool) {
print("inside viewWillAppear")
beginLoadView()
}
func beginLoadView(){
print("inside beginLoadView venue.name: \(venue?.name ?? "'venue' is nil")")
if venue != nil {
print("Venue var is not empty venue.name: \(String(describing: venue?.name))")
Utilities.run.showSVHUDWithStatus(uiView: self.view, status: "Discovering")
setupViews()
getCurrentLoggedUserProfile()
showHudAndStartUpdatingLocation()
observeUsersChanges()
} else {
print("Venue var is empty venue.name: \(String(describing: venue?.name))")
Utilities.run.showSVHUDWithStatus(uiView: self.view, status: "Discovering")
fetchNearestVenue()
getCurrentLoggedUserProfile()
}// end if-else
}//end func
}
}
Class VenueDetailsVC: UIViewController{
func presentDiscoverVC(){
guard let discoverVC = storyboard?.instantiateViewController(withIdentifier: "DiscoverVC") as? DiscoverVC else { return }
discoverVC.venue = self.venue!
discoverVC.showBackButton = true
DispatchQueue.main.async {
self.presentDetail(discoverVC)
}
}//end func
}
As I saw, discoverVC variable is not use to present and discoverVC variable you did set venue is diffirent DiscoverVC object presented. You can try print address of discoverVC and in viewWillAppear.

What is a good way to handle async requests in ReSwift/Redux

To make an asynchronous request a middleware is used in this case, it returns an error after a fixed amount of time.
The app state is properly updated the subscriber view controller presents the error.
On the next instance however this subscriber view controller is presented, it finds the error in the state - which is actually the error from the previous request and displays the error message before even the request is fired.
How to go about handling this case in ReSwift/Redux?
Store
let store = Store(
reducer: appReducer,
state: AppState(),
middleware: [requestMiddleware]
)
State
struct AppState: StateType {
var isRequestInProgress = false
var result: Result<Bool, NSError>?
}
Actions
struct RequestAction: Action {}
struct ReceiveAction: Action {}
struct ErrorAction: Action {
let error: NSError
}
Middleware
let requestMiddleware: Middleware<Any> = { dispatch, getState in
return { next in
return { action in
switch action {
case is RequestAction:
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
store.dispatch(ErrorAction(error: NSError(domain: "", code: -1, userInfo: nil)))
})
default:
break
}
return next(action)
}
}
}
Reducer
func appReducer(action: Action, state: AppState?) -> AppState {
var state = state ?? AppState()
switch action {
case is RequestAction:
state.isRequestInProgress = true
case let action as ErrorAction:
state.isRequestInProgress = false
state.result = .failure(action.error)
default: break
}
return state
}
The app
class ViewController: UIViewController {
#IBAction func presentControllerB(_ sender: Any) {
guard let viewController = storyboard?.instantiateViewController(withIdentifier: "ViewControllerB") else {
return
}
present(viewController, animated: true)
}
}
class ViewControllerB: UIViewController, StoreSubscriber {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
store.subscribe(self)
}
override func viewWillDisappear(_ animated: Bool) {
store.unsubscribe(self)
super.viewWillDisappear(animated)
}
func newState(state: AppState) {
showActivity(state.isRequestInProgress)
switch state.result {
case .none:
break
case .some(.success(_)):
break
case .some(.failure(let error)):
presentError(error)
dismiss(animated: true)
}
}
#IBAction func request(_ sender: Any) {
store.dispatch(RequestAction())
}
private func showActivity(_ show: Bool) {}
private func presentError(_ error: Error) {
print("Error")
}
}

How to assign a value to a class vairable from inside a block?

I am trying to set a value to a class variable from inside a block. But the value is not being set for some reason. To be frank I don't really know how to set value to a class variable from inside a block, so any help would be appreciated.
Here is my code:
class PhoneAuthViewController: UIViewController {
var verificationID: String = ""
#IBAction func activateButtonPressed(_ sender: UIButton) {
var phoneNumberString = ""
if phoneNumberField.text != nil {
phoneNumberString = phoneNumberField.text!
} else {
phoneNumberString = ""
}
//Checking if the phone number is in the right format
let phoneNumberFormatStatus = checkPhoneNumberFormat(phoneNumberData: phoneNumberString)
if (phoneNumberFormatStatus != true) {
//Showing the alert if the user enters invalid phone number
showInvalidPhoneNumberAlert(phoneNumberData: phoneNumberString)
}
verifyPhoneWithFireBase(phoneNumberData: phoneNumberString)
}
func verifyPhoneWithFireBase(phoneNumberData: String) {
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumberData, uiDelegate: nil) { (verificationID, error) in
if (verificationID != nil) {
self.verificationID = verificationID!
}
if let error = error {
self.showAlert(errorString: error.localizedDescription)
return
} else {
self.performSegue(withIdentifier: "otpVerificationScreen", sender: self.activateButton)
}
}
}
#IBAction func verifyOtp(_ sender: UIButton) {
print("\(self.verificationID) is self.verificationID")
print("\(verificationID) is verificationID")
}
}
The function verifyOtp doesn't print anything.

Live stream using AVPlayer not playing in iOS 11

I am trying to stream a music from remote url. I am trying to run this in iOS 11 but it not play the music.
ViewController
var session = AVAudioSession.sharedInstance()
var LQPlayer: AVPlayer?
let LOW_URL = URL(string: "http://someLInk.pls")! // not an original url provided at this time.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.avPlayerSetup()
}
func avPlayerSetup() {
do {
try session.setCategory(AVAudioSessionCategoryPlayback)
try session.overrideOutputAudioPort(.none)
try session.setActive(true)
} catch {
print("AVPlayer setup error \(error.localizedDescription)")
}
}
func initPlayer() {
LQPlayer = AVPlayer(url: LOW_URL)
print("player allocated")
}
func deAllocPlayer() {
LQPlayer = nil
print("player deallocated")
}
#IBAction func playBtn(_ sender: Any) {
initPlayer()
LQPlayer?.play()
}
#IBAction func pauseBtn(_ sender: Any) {
LQPlayer?.pause()
deAllocPlayer()
}
}
I set Allow Arbitrary Loads YES in info.plist.
Above code the URL I given is dummy. Actual url is working fine.
Working Code with Live Video Stream
#IBOutlet weak var player_View: UIView!
var LQPlayer: AVPlayer?
let LOW_URL = URL(string:"http://www.streambox.fr/playlists/test_001/stream.m3u8")!
override func viewDidLoad() {
super.viewDidLoad()
self.avPlayerSetup()
LQPlayer = AVPlayer.init(url: LOW_URL)
let avPlayerView = AVPlayerViewController()
avPlayerView.view.frame = self.player_View.bounds
avPlayerView.player = LQPlayer
self.player_View.addSubview(avPlayerView.view)
}
func avPlayerSetup() {
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
try audioSession.setActive(true)
} catch {
print("AVPlayer setup error \(error.localizedDescription)")
}
}
func initPlayer() {
LQPlayer = AVPlayer(url:LOW_URL)
print("player allocated")
}
func deAllocPlayer() {
LQPlayer = nil
print("player deallocated")
}
#IBAction func playBtn(_ sender: Any) {
// initPlayer()
LQPlayer?.play()
}
#IBAction func pauseBtn(_ sender: Any) {
LQPlayer?.pause()
deAllocPlayer()
}

Bonjour Service Browser with Swift does not fetch serviceinfo

The service I want to connect to is published via Bonjour.
I can find all the info with the Bonjour Browser, however if I try to gather the data programmatically, the only value I get, is the name of the service.
The NetService delegate is set and the function netServiceWillPublish is called.
The functions DidNotPublish or DidPublish are not executed.
The function netServiceBrowser gets all published netServices, but all properties are set to the default value of the datatype.
import UIKit
class BMNSDelegate : NSObject, NetServiceDelegate {
func netServiceWillPublish(_ sender: NetService) {
print("netServiceWillPublish:\(sender)"); //This method is called
}
func netService(_ sender: NetService, didNotPublish errorDict: [String : NSNumber]){
print("didNotPublish:\(sender)");
}
func netServiceDidPublish(_ sender: NetService) {
print("netServiceDidPublish:\(sender)");
}
func netServiceWillResolve(_ sender: NetService) {
print("netServiceWillResolve:\(sender)");
}
func netService(_ sender: NetService, didNotResolve errorDict: [String : NSNumber]) {
print("netServiceDidNotResolve:\(sender)");
}
func netServiceDidResolveAddress(_ sender: NetService) {
print("netServiceDidResolve:\(sender)");
}
func netService(_ sender: NetService, didUpdateTXTRecord data: Data) {
print("netServiceDidUpdateTXTRecordData:\(sender)");
}
func netServiceDidStop(_ sender: NetService) {
print("netServiceDidStopService:\(sender)");
}
func netService(_ sender: NetService,
didAcceptConnectionWith inputStream: InputStream,
outputStream stream: OutputStream) {
print("netServiceDidAcceptConnection:\(sender)");
}
}
class BMBrowserDelegate : NSObject, NetServiceBrowserDelegate, NetServiceDelegate {
func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser,
didFind netService: NetService,
moreComing moreServicesComing: Bool) {
let nsnsdel = BMNSDelegate()
netService.delegate = nsnsdel
netService.resolve(withTimeout: 1)
print(netService.domain) // local.
print(netService.name) // This property is correct
print(netService.type) // _http._tcp.
print(netService.addresses) // Optional([])
print(netService.hostName) // nil
print(netService.port) // -1
print(moreServicesComing) //false
}
}
let SERVICE_TYPE = "_http._tcp."
let BM_DOMAIN = "local."
let browser = NetServiceBrowser()
let nsbdel = BMBrowserDelegate()
browser.delegate = nsbdel
browser.searchForServices(ofType: SERVICE_TYPE, inDomain: BM_DOMAIN)
RunLoop.current.run()
The error is that the services which are found in the ServiceBrowserDelegate function are not saved anywhere and therefore are discarded at the end of the function.
I found a working example here:
https://github.com/mattneub/Programming-iOS-Book-Examples/blob/61f0c753a080040e4a74b912e6c18dd97fe8bcaa/bk2ch24p853bonjour/ch37p1101bonjour/ViewController.swift
class ViewController: UIViewController, NetServiceBrowserDelegate, NetServiceDelegate {
var nsb : NetServiceBrowser!
var services = [NetService]()
#IBAction func doButton (_ sender: Any!) {
print("listening for services...")
self.services.removeAll()
self.nsb = NetServiceBrowser()
self.nsb.delegate = self
self.nsb.searchForServices(ofType:"_daap._tcp", inDomain: "")
}
func updateInterface () {
for service in self.services {
if service.port == -1 {
print("service \(service.name) of type \(service.type)" +
" not yet resolved")
service.delegate = self
service.resolve(withTimeout:10)
} else {
print("service \(service.name) of type \(service.type)," +
"port \(service.port), addresses \(service.addresses)")
}
}
}
func netServiceDidResolveAddress(_ sender: NetService) {
self.updateInterface()
}
func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didFind aNetService: NetService, moreComing: Bool) {
print("adding a service")
self.services.append(aNetService)
if !moreComing {
self.updateInterface()
}
}
func netServiceBrowser(_ aNetServiceBrowser: NetServiceBrowser, didRemove aNetService: NetService, moreComing: Bool) {
if let ix = self.services.index(of:aNetService) {
self.services.remove(at:ix)
print("removing a service")
if !moreComing {
self.updateInterface()
}
}
}
}