NavigationLink work on simulator but don't work on real device iPhone - navigationview

I am new in SwiftUi and i try to run the code below.On simulator work well, but when try to run on real device (iPhone/iPad) work one time. The first time i can go to second view, but when i return with "
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView{
NavigationLink(destination: Text("Second view")) { Text("First view")}
}
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif

Related

SwiftUI : How I can set refreshable for my Scrollview without List

import SwiftUI
struct HomeView: View {
#StateObject var vm = NewsViewModel()
let dataService = NewsDataService.instance
init() {
dataService.apiCall(text: "Korea")
}
var body: some View {
NavigationView {
ScrollView(.vertical, showsIndicators: false) {
SearchView()
VStack {
Divider()
if let newsArray = vm.newsArray?.articles {
ForEach(newsArray) { news in
NewsRowView(news: news)
}
}
}
}
.navigationTitle("News")
.navigationBarTitleDisplayMode(.automatic)
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
Hi, I tried to find refresh for my scrollview.
But, most of the examples were capable with List.
As you can see my code, I makde my list with HStack children View.
Because of that, I can't use the ".refreshable" modifier.
So, I want to know how I can set that in my view.
And If I can, I want to see detailed code as well!
Thanks.
You could use refreshable like this in your NewsRowView. Keep in mind you would need to make sure you are using ObservableObject where necessary so that it will give you the new data once it's updated.
.refreshable {
Task {
let dataService = NewsDataService.instance
dataService.apiCall(text: "Korea")
}
}

SwiftUI OpenWeatherApi App show no content

Im new to swift development and I can't make myself pass through this. I run my app and by pressing the "action" button I see no change on my text which should be the current temperature. And It's giving me an error "nw_protocol_get_quic_image_block_invoke dlopen libquic failed"
My code:
struct ContentView: View {
#State var temp = Int()
func CallApi(){
let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=budapest&appid=#########################################")
URLSession.shared.dataTask(with: url!){data, response, error in
if let data = data {
if let DecodedData = try? JSONDecoder().decode(Api.self, from: data){
self.temp = DecodedData.main.temp
}
}
}.resume()
}
struct Api: Codable, Hashable{
var main: DataStructre
}
struct DataStructre: Codable, Hashable {
var temp: Int
}
var body: some View {
Text("\(temp)")
Button("Idojaras"){CallApi()}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
If you use do/try/catch instead of try?, you can get a useful error message.
do {
let DecodedData = try JSONDecoder().decode(Api.self, from: data)
self.temp = DecodedData.main.temp
} catch {
print(error)
}
In this case, I get:
Parsed JSON number <304.31> does not fit in Int.
Changing the type of temp (in both the #State variable and the DataStructre) fixes the issue.
In general, I'd recommend pasting your JSON into app.quicktype.io, which will give you generated models with the correct types/structures.
Slightly unrelated to your issue, but you may want to look into using dataTaskPublisher and Combine in SwiftUI rather than dataTask (https://developer.apple.com/documentation/foundation/urlsession/processing_url_session_data_task_results_with_combine). Also, function names in Swift are generally lowercased.

SwiftUI New File and Passing a value

I have a value as $freq being passed to a new SwiftUI file as frequencyValue, however the file called DipoleView is getting the error below.
This is in the ContentView:
HStack{
NavigationLink(destination: DipoleView(frequencyValue: $freq)) {
Text("Dipole")
.font(.title)
.fontWeight(.bold)
.foregroundColor(.white)
.frame(width: 150.00, height: 50.0)
.background(Color.green)
.cornerRadius(25)
.shadow(radius: 10.0)
.padding()
}
The code below is at the base of the other file called DipoleView and it requires some code concerning the passing of the variable from the ContentView..
#if DEBUG
struct DipoleView_Previews: PreviewProvider {
static var previews: some View {
**DipoleView(frequencyValue: <#Binding<String>#>)**
}
}
#endif
The above DipoleView(frequencyValue: <#Binding#>) I need to place some code here but I am not sure what it is suppose to be?
Hoping someone can help a Newby.
Cheers.
Since you're just trying to create a preview, you can use a constant binding:
#if DEBUG
struct DipoleView_Previews: PreviewProvider {
static var previews: some View {
DipoleView(frequencyValue: .constant("some frequency value"))
}
}
#endif
This makes the binding immutable in your preview, but you shouldn't really need a mutable binding when previewing in the canvas.

Is it possible to programatically create a xaml page?

I might write no sense on the next lines:
I tried to derive a struct named mainpage from winrt::Windows::UI::Xaml::Controls::Page and pass it to winrt::xaml_typename<>(), in "<>" is mainpage.
It will be understandable when you look at the code:
Point number 1 "(1)" is the mainpage.h file, is very short.
Point number 2 "(2)" is the App.cpp file, it only has the necessary.
//(1) mainpage.h
#pragma once
#include "pch.h"
struct mainpage : winrt::Windows::UI::Xaml::Controls::Page
{
mainpage() {
winrt::Windows::UI::Xaml::Controls::Button thebutton = winrt::Windows::UI::Xaml::Controls::Button();
thebutton.Click([&](const IInspectable& sender, const winrt::Windows::UI::Xaml::RoutedEventArgs& event_arg)
{
thebutton.Content(winrt::box_value(L"Clicked"));
});
}
};
//(2) App.cpp
#include "pch.h"
#include "mainpage.h"
struct App : winrt::Windows::UI::Xaml::ApplicationT<App>
{
void OnLaunched(const winrt::Windows::ApplicationModel::Activation::LaunchActivatedEventArgs& event_arg)
{
winrt::Windows::UI::Xaml::Controls::Frame root_frame{ nullptr };
winrt::Windows::UI::Xaml::UIElement content = winrt::Windows::UI::Xaml::Window::Current().Content();
if (content)
{
root_frame = content.try_as<winrt::Windows::UI::Xaml::Controls::Frame>();
}
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (root_frame == nullptr)
{
// Create a Frame to act as the navigation context and associate it with
// a SuspensionManager key
root_frame = winrt::Windows::UI::Xaml::Controls::Frame();
root_frame.NavigationFailed({ this, &App::OnNavigationFailed });
if (event_arg.PreviousExecutionState() == winrt::Windows::ApplicationModel::Activation::ApplicationExecutionState::Terminated)
{
// Restore the saved session state only when appropriate, scheduling the
// final launch steps after the restore is complete
}
if (event_arg.PrelaunchActivated() == false)
{
if (root_frame.Content() == nullptr)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
root_frame.Navigate(winrt::xaml_typename<mainpage>(), box_value(event_arg.Arguments()));
}
// Place the frame in the current Window
winrt::Windows::UI::Xaml::Window::Current().Content(root_frame);
// Ensure the current window is active
winrt::Windows::UI::Xaml::Window::Current().Activate();
}
}
else
{
if (event_arg.PrelaunchActivated() == false)
{
if (root_frame.Content() == nullptr)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
root_frame.Navigate(winrt::xaml_typename<mainpage>(), box_value(event_arg.Arguments()));
}
// Ensure the current window is active
winrt::Windows::UI::Xaml::Window::Current().Activate();
}
}
}
void App::OnNavigationFailed(const IInspectable&, const winrt::Windows::UI::Xaml::Navigation::NavigationFailedEventArgs& event_arg)
{
throw winrt::hresult_error(E_FAIL, winrt::hstring(L"Failed to load Page ") + event_arg.SourcePageType().Name);
}
};
int __stdcall wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) {
winrt::Windows::UI::Xaml::Application::Start([](auto &&) { winrt::make<App>(); });
}
If it is not possible, how can I properly create a page?
It is simple if you have installed the CppWinRT VSIX. Then create a "View model" and edit the files. You shouldn't derive the struct from the winrt::Windows::UI::Xaml::Controls::Page class because winrt::xaml_typename<> needs a WinRT class in <>.

Pause application in QML when app is in background Symbian

I want to know of any pure QML way to find out whether the application is in the background or not and then accordingly stop or play music. In meego the alternate way to do is through the PlatformWindow Element but it does not exist in Symbian QML. Help needed please
Finally I got it working :) and i did it though Qt way... here are the steps
1) Create a class MyEventFilter
class myEventFilter : public QObject
{
bool eventFilter(QObject *obj, QEvent *event) {
switch(event->type()) {
case QEvent::WindowActivate:
emit qmlvisiblechange(true);
qDebug() << "Window activated";
bis_foreground=true;
return true;
case QEvent::WindowDeactivate:
emit qmlvisiblechange(false);
qDebug() << "Window deactivated";
bis_foreground=false;
return true;
default:
return false;
}
}
void dosomething();
private:
int something;
public:
bool bis_foreground;
Q_OBJECT
public slots:
Q_INVOKABLE QString checkvisibility() {
if (bis_foreground==true) return "true";
else return "false";
}
signals:
void qmlvisiblechange(bool is_foreground);
};
2) Then in main.cpp include this file include the class and add setContext propery like this
context->setContextProperty("myqmlobject", &ef);
3) in qml file call it like this:
Item {
id: name
Connections
{
target:myqmlobject
onQmlvisiblechange:
{
if(is_foreground)
{
//dont do anything...
}
else
{
playSound.stop()
}
}
}
}
Enjoy :)
Why do you need a pure QML way?
You can detect if an application has been sent to the background by installing an event filter.
Check: http://www.developer.nokia.com/Community/Wiki/Detecting_when_a_Qt_application_has_been_switched_to_the_background_and_when_resumed
For a "pure" QML way, there is the Symbian QML element:
http://doc.qt.nokia.com/qt-components-symbian/qml-symbian.html
It has a foreground property that indicates whether the app is in the foreground or in the background. You can try connecting to onForegroundChanged.
From the documentation, the Symbian element is not "creatable". It exists as a context property named symbian. So a sample usage would be:
import QtQuick 1.1
import com.nokia.symbian 1.1
PageStackWindow {
id: window
initialPage: MainPage {tools: toolBarLayout}
showStatusBar: true
showToolBar: true
function appForegroundChanged() {
console.log("Foreground: " + symbian.foreground)
}
function appCurrentTimeChanged() {
console.log("Current time: " + symbian.currentTime)
}
Component.onCompleted: {
symbian.currentTimeChanged.connect(appCurrentTimeChanged)
symbian.foregroundChanged.connect(appForegroundChanged)
}
ToolBarLayout {
id: toolBarLayout
ToolButton {
flat: true
iconSource: "toolbar-back"
onClicked: window.pageStack.depth <= 1 ? Qt.quit() : window.pageStack.pop()
}
}
}