Blog Grid
- Home
- Blog Grid
Make Vue.js SPA with Laravel SEO Friendly
I have been working on my new startup Triphie, itâs an interactive and collaborative trip planner that helps you and your friends plan your dream trips in a very smooth and convenient way. I used Laravel and Vuejs SPA for that, and one of the challenges Iâve faced is how to make my website SEO friendly.
If you have ever tried to build a website using Single page application using Vuejs and Larave, then you might already know that making it SEO-friendly is one of the challenges that you might encounter.
So how can you overcome this challenge and make your website SEO friendly?
First, letâs discuss how your website can be SEO friendly and then discuss the downfalls that Vuejs has regarding this,
How do Search engines rank your website?
Search engines crawl your website and try to understand its content, then they will index it so that if any user later searches for any keyword in the search engine they will match your website content to that keyword.
That means to get your website indexed, search engines should be able to crawl your website links and parse its content.
One more thing that helps your website to be ranked and viewed by search engines and social media are meta tags, they have title, description, and image, that are responsible for how your links will be viewed when it appears on search results or on the newsfeed of Facebook and Twitter.
This is an example of one of the links to our blog posts on Triphie
What downfalls Vuejs has when it comes to SEO?
We all know that Vuejs is a JavaScript framework, and it is a client-side rendering framework, that means you when open any link of your website the page content will not be visible until the page is being loaded by the browser, so in most cases, search engines will not be able to fetch your page content, thus it will not be able to index it.
So how we overcome this?
Most search engines (like Google) now have some ways to run JavaScript and also it will index your page content. However this is not everything, social media platforms like Facebook and Twitter still canât run JavaScript, hence your website links will not get parsed and viewed correctly, that because your website meta tags are not visible in your page content. đ
To solve this you can use libraries like vue-meta where you will be able to define your meta tags for each page separately, yet we still have the issue of the page isnât being rendered on the server side.
Then shall you stop using Vuejs?
No not yet, there are some ways to solve this issue, one of them is server-side rendering, which will render your page content before itâs sent to the client.
I can hear you thinking then why we used vuejs in the first place if we want to render it on the server side?
Yes, you’re right, I donât prefer this solution either, as it has some complications and you have to double your efforts sometimes.
How we solved this at Triphie?
Instead of using so many libraries, I came up with a very simple solution that solved most of my problems with a couple of lines of codes, I didnât use vue-meta or server-side rendering, instead, I used the normal Larvel blade file, as you already know your SPA should have one entry blade file that has your app container, and this is the only page that will be loaded from server side and it will have itâs own meta tags.
And here comes the trick where I used this file to render meta tags for all of my pages,
<!-- Open Graph / Facebook -->
<meta property="og:type" content="website">
<meta property="og:url" content="your website url">
<meta property="og:title" content="title">
<meta property="og:description" content="description">
<meta property="og:image" content="image path">
These are the meta tags for Facebook, you should have more for Twitter and search engines like google.
As you can see the issue here is, that they are not dynamically changing for each page, so what I have done here is, replaced the previous one with this
<!-- Open Graph / Facebook -->
<meta property="og:type" content="website">
<meta property="og:url" content="{{ $meta['url'] }}">
<meta property="og:title" content="{{ $meta['title'] }}">
<meta property="og:description" content="{{ $meta['description'] }}">
<meta property="og:image" content="{{ $meta['image'] }}">
Now we are getting meta tags dynamically from the server, but how the server will know which page is which?
Inside your SinglepageController index method, we check the route that is calling this method and then we return the meta tags accordingly.
public function index() {
$meta = [
"title" => config('app.title'),
"description" => config('app.description'),
"url" => config('app.url'),
"image" => asset('imgs/cover.jpg')
];
$path = request()->path();
if (str_contains($path, 'blog/post/')) {
$post_id = str_replace('blog/post/', '', $path);
$post = Post::find($post_id);
if ($post) {
$meta = [
"title" => $post->title,
"description" => $post->snippet,
"url" => config('app.url') . $path,
"image" => $post->cover
];
}
}
return view('app', ['meta' => $meta]);
}
And Voila !!!
This simple method was very helpful for us in Triphie, I hope it will be helpful for you as well. If you have any better way of solving this please do share it in the comments down below
Donât forget if you find this useful to clap it and share it with your friends who might be interested in this as well, and most importantly donât forget to follow me for more đ
Unit Test View Controllers the easy way in Swift
When it comes to unit test view controllers, people think of using UI Tests instead of Unit Tests. However UI Test is not the answer for everything related to UIKit, and today we will discuss what are the key things to tell you what and when to use each one of them.
What to unit test in view controllers
View controllers form most of our project, therefore unit test viewController is essential and will lead to better code quality.
Just remember you canât use unit tests for everything related to UIKit, for instance, you shouldnât use unit tests to test background colors, font size, text color, or even Auto-layout constraints.
On the other hand, we use Unit Test to test if Label text is correct, Button is enabled, IBOutlet exists, and Navigations between ViewControllers
Before we start writing tests first we should load View controllers, and that will get us into three different methods of creating them
and today we will discuss all of them
Now letâs learn how to do the magic.
Setup our Environment
All we need to start by writing unit tests for view controllers is to create a new Xcode project, name it something like UnitTestViewControllers and remember to enable Include Tests.
Now go to UnitTestViewControllersTests.swift and remove all the methods inside it, and hit (remember always to select simulator, not a physical device when testing) to run the test and make sure that everything is working, you should get the same result as here
Setup Storyboard based view controllers
Firstly Let’s start by creating a view controller by going to File->New->File
and chose Cocoa Touch Class
and then select UIViewController
as Subclass and give it the name StoryboardViewController
like this
Now For simplicity, we will use Main.storyboard
, now go and add the view controller by dragging and dropping it from the library menu
And give it the class of StoryboardViewController
and also storyboard ID as StoryboardViewController
from the inspectors
area
Now add a UILabel
to the storyboard and link it to the code
Load Storyboard based view controllers into tests
This should be very straightforward, all you have to do now is go to UnitTestViewControllersTests.swift
and write a test case for loading the storyboard view controller and then hit you should get a green mark for this
Now itâs time to test if the Label
is loaded, we do that by adding an assertion and then running the test again
As you can see the test has failed because our view controller is not yet loaded we should ask it to load the view first by adding sut.loadViewIfNeeded()
before the assertion and that will load the view controller as well as the IBOutlet connection for the label.
Now rerun the test and Voila, tests passed again.
Setup XIB based view controllers
Let’s set up our XIB view controller, well this should be pretty much the same as the storyboard one, go to File->New->File
and chose Cocoa Touch Class
and then select UIViewController
as Subclass but this time check the Also create XIB file
and give it the name XIBViewController
like this:
Now you should have two files
Testing XIB ViewController
Now after that do the same step as 2.3 Add Outlet
and make sure to link it to the code, now go to UnitTestViewControllersTests.swift
and add a new method this time to test the XIB view controller
And after running the test you should see the green mark again to know that all has passed.
Setup Code based view controllers
Let’s set up our Code view controller, go to File->New->File
and chose Cocoa Touch Class
and then select UIViewController
as Subclass and give it the name CodeViewController
, this is different from the two types before that it doesn’t have an outlet to link, so we need to set up our UI in code, so after creating it open the file and just add the following
Now to test this just go to the Tests file and add the final method
And Hooray now we know how to load and test all the 3 types of ViewControllers.
Conclusion
We have seen today how to set up and load ViewController for testing, later we will talk about testing navigation between ViewControllers as well as how to write testable view controllers so stay tuned.
You can find the code on GitHub.
Before you go…
If you liked this article please clap and share it with friends.
And if you wanted to have a discussion or reach me you can go to my website and get in touch.
Start with Test-driven development in Swift
Previously we talked about Unit Testing and how to write them, today we will talk about Test-driven development in Swift.
One of the methodologies in software development that has been developed by Kent Beck is the âExtreme Programmingâ, based on 12 rules or practices. One of them is that developer has to write a unit test and all of the software has to be tested, and all tests have to pass before the developer takes the green light to release to the customer.
Unit Test vs TDD
What is the difference between Unit Test and Test-Driven Development? In Unit Test you write code to test your code. You first write code then you write tests to verify your logic and code that you wrote. But in TDD, you first write tests that fail and then write code to make the tests pass, and then you refactor your code.
You must begin by writing a unit test for the functionality that you intend to write. But by rule 2, you canât write very much of that unit test. As soon as the unit test code fails to compile, or fails an assertion, you must stop and write production code. But by rule 3 you can only write the production code that makes the test compile or pass, and no more.
What is Test-driven development?
TDD is where you first write a test that fails, and then you write code to make it pass, and then you refactor your code to be as simple as possible.
Writing automated tests is seen as not real work and boring compared to building new features. TDD, however, turns testing into a design activity. We use our tests to make sure our code is doing what we want it to do. It also keeps code as simple as possible so itâs easier to understand and modify, especially since developers spend more time reading code than writing it.
Using TDD to develop gives us feedback about the quality of both its implementation (does it work) and design (is it well structured).
An example of TDD
We will use the same Calculator example we wrote in the previous post. Now when you open the project and run the test it should pass.
Letâs start by writing the acceptance criteria for our tests. We have to answer the following questions:
- Precondition: What is the system state before we invoke the method?
- Invocation: What is the method signature? What is the input and what is the output of the method?
- Assertion: What is the expected result of the method?
In our Calculator example, we want to add new methods, for example, we want to add the power method, so letâs answer the previous questions:
- Precondition: None.
- Invocation: The method should take two integers, x, and y, and return an integer which is the result of x to the power of y.
- Assertion: The result should be an integer equal to x to the power of y.
Red step
Go to CalculatorTest.swift and write the following code:
func testPowerMethod() throws {
let calcualtor = Calcualtor()
let result = calcualtor.power(x: 5,y: 2)
}
Before you complete writing the test you will see the red alert to tell you that there is something wrong, so you have to start writing some code here.
Green Step
Go the Calculator.swift file and create the method called power.
func power(x: Int, y: Int) -> Int {
return 0
}
Run the test again, and now it will be green:
Notice we did not focus on any thing except making the test pass.
Red, Again
Now letâs continue with our test, and write the assertion.
func testPowerMethod() throws {
let calcualtor = Calculator()
let result = calcualtor.power(x: 5,y: 2)
XCTAssertEqual(result, 25)
}
Run the test again using âCommand + U â and it will fail again. Because we did not write the body of the power function to give the correct result.
Have the Green Light again
To have the green light again we should go to Calculator.swift file and implement the power method body like this:
func power(x: Int, y: Int) -> Int {
var result = 1
var i = y
while (i != 0) {
result *= x
i -= 1
}
return result
}
And it when running the test again it will turn green.
Refactor the code
After we get the correct result from the method now itâs time to refactor it to make sure that your code is as simple as possible. So how can we do that here?
Letâs get ride of the for-loop and try to use the built it pow(_, _) method in Swift. The problem is this method accept doubles instead of integers so we have to convert them:
func power(x: Int, y: Int) -> Int {
return Int(pow(Double(x), Double(y)))
}
And now we are done!
Conclusion
As you can see, Test-Driven Development is simple and easy. Maybe you would feel itâs unnecessary and you can skip parts of it, but you canât because it will not be TDD any more.
All you have to remember is the Red, Green, Refactor, and thatâs it. You focus on writing your tests and code and nothing else, and the more you work with TDD the more you will feel that you canât live without it.
Before you goâŚ
If you liked this article please do clap and share it with friends.
And if you wanted to have a discussion or reach me you can go to my website and get in touch.
Originally published at https://www.nouraraar.com on July 13, 2020.
Your First Unit Tests: Write IOS Unit Unit the easy way
We all should write Unit Tests if we want our code to work and keep working.
Why you should do Unit Tests
You are planning to build an app. You start collecting features and drawing some sketches. At some point, you start coding. After you have set up the project, you start implementing the required features of the app, but you ended up with tons of bugs instead of features.
You rushed up and started to add breakpoints and waited for a miracle to happen and fix all of the bugs for you. Then, after thousands of reruns, you wished for some black magic to test your app and fix what you have committed.
What are Unit Tests
Automatic unit tests are the black magic you wished for. They execute code, but without the need to add breakpoints and navigate to the screen to test. Instead of running the app over and over again, you write tests with different input data and let the computer test your code in the blink of an eye. We will see how this works in a simple example.
What you should test?
The first thing to know before writing tests is you should know what you need to test.
Usually, you have to test new features, events, or components of the app you plan to change.
But in general, you will have to write tests for:
- The main functionality of the app
- The most common workflow
- Bug fixes
- Edge case and boundary conditions
Implementing a Unit Tests example
Open Xcode and go to File -> New -> Project. Navigate to iOS -> Application -> Single View App, and click on Next. Put in the name FirstUnitTest, select the language Swift, and check Include Unit Tests. Uncheck Use Core Data and Include UI Tests, and click on Next. The following screenshot shows the options in Xcode:
When done you will see this result in the Xcode navigator:
What is inside the FirstUnitTestTests?
If you opened the FirstUnitTestTests.swift file from Xcode Navigator you should see this at the top of the file:
import XCTest @testable import FirstUnitTest
Every test case needs to import the XCTest framework. It defines the XCTestCase class and the test assertions that you will see later in this chapter.
The second line imports the module FirstUnitTest. All the code you write for the app will be in this module. By default, classes, structs, enums, and their methods are defined as internal. It means that they can be accessed within the module. While the test code lives outside of the module. To be able to write tests for your code, you need to import the module with the @testable keyword. This keyword makes the internal elements of the module accessible to the test case.
You will see four methods:
- setUpWithError: You should add your setup code here, this method is called before the invocation of each test method in the class.
- tearDownWithError: You should put the teardown code here. This method is called after the invocation of each test method in the class.
- testExample: This is an example of a functional test case. Every test case should have the test keyword at the beginning.
- testPerformanceExample: This is an example of a performance test case. You will add the code to test performance inside the self.measure closure.
In the beginning, itâs good practice to have a test case for each class in the main target.
Letâs write some code to test
Letâs create our class to test it go to File -> New -> File
and select Swift File, name it Calculator.swift
Letâs write a couple of simple methods to test, they will be simple so we can focus on the purpose of this which is to see how to write tests.
Write down this code in the Calculator.swift file:
class Calcualtor { func sum(x: Int, y: Int) -> Int { return x + y } func multi(x: Int, y: Int) -> Int { return x * y } }
Now letâs get our hands dirty.
Write your first Unit Tests
You can write the test function inside FirstUnitTestTest.swift or create a new test case class for the Calculator class. It is preferred to create a single test case class for every class.
In case you wanted to create a new test case class go to File -> New -> File -> Unit Test Case Class and give it the name CalculatorTest.swift.
You will find all the methods we talked about before but you will not see:
@testable import FirstUnitTest
Now add it to be able to use the Calculator.swift file.
In real-life testing, you can delete the previous four methods and start writing your own.
Write this simple method:
func testSumMethod() throws { let calcuator = Calcualtor() let result = calcuator.sum(x: 5, y: 11) XCTAssertEqual(result, 16) }
Run Your Unit Tests
You can run your unit tests from four different places:
- Product ⸠Test or Command-U. Both of these run all test classes.
- The arrow button in the Test navigator.
- The diamond button is in front of the test function.
- The diamond button in front of the class name will run all the test functions inside the class.
If everything is ok you should see something like this:
XCTAssertEqual is trying to test if two expressions are equal and throw an error if not.
How to Improve Unit Tests
There are some points to keep in mind while performing unit testing:
- Use consistent naming conventions and test one code at a time.
- Make sure that there is a corresponding unit test case for a module if there is any change in the code.
- All the bugs must be fixed before moving to the next phase.
- Itâs better to test as you commit a code to avoid errors.
- Focus more on the tests that affect the behavior of the system.
Important built-in assert functions
The most important assert functions are:
- XCTAssertTrue(_:_:file:line:): This asserts that an expression is true.
- XCTAssertFalse(_:_:file:line:): This asserts that expression is false
- XCTAssertEqual(_:_:_:file:line:): This asserts that two expressions are equal
- XCTAssertEqualWithAccuracy(_:_:accuracy:_:file:line:): This asserts that two expressions are the same, taking into account the accuracy defined in the accuracy parameter
- XCTAssertNotEqual(_:_:_:file:line:): This asserts that two expressions are not equal
- XCTAssertNil(_:_:file:line:): This asserts that an expression is a nil
- XCTAssertNotNil(_:_:file:line:): This asserts that an expression is not nil
- XCTFail(_:file:line:): This always fails
Conclusion
It is clear that Unit Tests cannot and should not be avoided. Rather, developers should opt for Test-Driven Development where they write the test and then write the code. You just need to get suitable tools to further reduce your testing efforts.
If you like this article please clap and share it with friends.
If you want to have a discussion or reach me you can go to my website and get in touch
HOW DEVELOPER SHOULD DESIGN AND THINK LIKE DESIGNER
today we will talk about how the developer should read the design to build better apps, and do a more complex and pixel-perfect design
For a long time, the design represented a difficult challenge for the developer, and because the developer always tries to think in a way that they fill in logic, the design sometimes contradicts this aspect and needs more on the creative side But before we continue on how to find a solution to this issue, let us know why design is important
WHY IS DESIGN IMPORTANT?
The design is of great importance for several reasons 1. Users see and care about the design, they donât see the complex code:
The first thing the user will judge when he opens your app is the design, the better the design the more likely the user will love your app so itâs more important than code 2. The user experience is crafted by design:
itâs clear that every idea and a new feature in the company has to be run by the designer who will do research and build the design in a way that will make the user experience better.
after we know the importance of the design letâs go through the current process of designing and try to improve it đ
HOW DO DEVELOPERS DO THINGS CURRENTLY?
first, he will get the design files from the designer, âwho uses tools like sketch and Zeplinâ
and start to mock them up using his development tools like (Xcode, android studio, or any text editor for web developers)
Example of an app screen:
as we can see in an Example for a signup page here the developer will start building the components of the page
Simple Component Example:
each component has multiple attributes like
1. Font 2. Text Color 3. Border Color 4. Background Color 5. Placeholder Color and Font 6. Multiple States (enabled, disabled, selected)
now the developer will start reading these attributes for each component from design application to code
WHY IS THIS NOT RECOMMENDED?
- The design takes 2â3 of the time when building any project
- High chance of human errors
- Not easy to build a complex design
- the high effort required to change and maintain the design
HOW MUCH TIME DOES IT TAKE? TO BUILD A SIMPLEÂ DESIGN?
this number is related to the developer and will change from one to one depending
on the developer speed of building the things
but as an average and just for comparing purposes
that mean for average it will take about 32 days to build the design
HOW CAN WE REDUCE THE TIME NEEDED? AND BUILD BETTER AND MORE COMPLEX DESIGNS?
since this is a designer’s process so it is better to do it their way, what does that mean?
designers build things using symbols that can be reused everywhere,
which means they build the symbol once and have it where ever they want and when they need to use it again, they just call the symbol name and if they wanted to do some changes, they just update the symbols file and it will be reflected everywhere.
INTRODUCING ATOMIC DESIGN METHODOLOGY
Atomic design is a methodology composed of five distinct stages working together
to create interface design systems in a more deliberate and hierarchical manner.
The five stages of atomic design are:
Atomic design is not a linear process, but rather a mental model to help us think of our user interfaces as both a cohesive whole and a collection of parts at the same time. Each of the five stages plays a key role in the hierarchy of our interface design systems. Letâs dive into each stage in a bit more detail.
HOW DO WE PUT IT INTO PRACTICE?
as we can see it is just a way of thinking and organizing your elements and style,
so instead of starting building the design from top-down (building the pages then the elements),
we go the opposite way down top, which means we start from the atoms
Atoms are the simplest element such as labels, buttons, inputs and images
this is the Current Way To build things so in order to build the design we have to go through every element and component in the design that will result as we already found around ~ 15000 operations to build
so instead of building that number of components we only build the unique components and use them around the app and as a result
so the first thing to ask your designer for is the colors, fonts, and all unique components
Colors design file:
Components design file:
HOW MUCH TIME DO WE USE NOW? CURRENTLY, WE HAVE ABOUT 20 UNIQUE COMPONENTS
since we donât care anymore about the number of screens and number of components in it we only care about the number of unique components in our design the number of operations goes down to ~900 instead of ~15000 and that is a huge improvement in the designing process
WHAT HAVE WE ACHIEVED NOW?
- our design now is more organized and readable
- the number of operations reduced to 1â10 of the old way
- now can build more complex designs from what we already got
- now can focus more on the logic, not the design
- the time to maintain and change the design goes from days to hours
since you have now only to change the unique components only from one place
now as a result we are now agreed that
let the design process for designers
and focus on your code and logic of the app
And what about you, how do you build your design?
write a comment below and share your way with us and give your feedback about this way
and donât forget if you liked the post to give some claps đ
and remember do not hesitate to contact me if you have any questions or feedback
ITMS-90809: Deprecated API UsageâââMigrate from UIWebview to WKWebView
If you are an IOS developer and you are using UIWebView and constantly deploying apps to the app store that means you definitely faced a warning from apple telling you
ITMS-90809: Deprecated API Usage - Apple will stop accepting submissions of app updates that use UIWebView APIs starting from December 2020. See https://developer.apple.com/documentation/uikit/uiwebview for more information.
That means you should start to get rid of all the UIWebView and replace them with WKWebView.
And starting from Aprile 2020 you will not be able to submit any app using uiwebview
So How you will do it
1. First if you are using it in your code
All you have to do is to start migrating from UIWebView to WKWebview
You need to replace this code
With this code
2. If you are using 3rd party libraries
Migrating from UIWebView to WKWebView might seem relatively straightforward, but you probably use some 3rd party libraries and they might also contain UIWebView.
You need to find all of them and update them, if available or replace them. This process is not exactly trivial. If you use 3rd party libraries as code, for example via Cocoapods, you can do a text search for UIWebView in their sources.
One of the most used libraries is RxSwift using the UIWebView in version prior to 5.1.0
so you can use this command to find all of these libraries
grep -r 'UIWebView'Â .
Then check the result that you got and try to upgrade all the pods and thatâs it
I hope this will help you đ