Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Real DOM Vs Virtual DOM Vs Shadow DOM In JavaScript Frameworks).
In this note series, we will understand the differences between the Real DOM, Virtual DOM and Shadow DOM in JavaScript Frameworks.
So Let’s begin.
Real DOM Vs Virtual DOM Vs Shadow DOM
Real DOM
Virtual DOM
Shadow DOM
Definition
It is the representation of a document/webpage/web application’s user interface as a tree data structure (node and objects).
It is a virtual representation of the real DOM as a tree data structure (node and objects).
The Shadow DOM can be thought of as a “DOM within a DOM”. It is a separate DOM tree with it’s own elements and styles, fully separate from the main DOM.
Usage
The Real DOM is used in every browser.
The virtual DOM is employed in many front-end frameworks and libraries like React, Vue etc.
Web components use the concept of. Shadow DOM.
The purpose of each technology
It provides a simpler, more programmatic method of representing web pages.
The virtual DOM was created to address performance problems with webpages and web application that resulted from the constant re-rendering of the whole DOM whenever DOM elements were updated.
The Shadow DOM was designed to contain and isolate DOM elements, hence preventing direct DOM leakage of those elements and their dependent data.
Implementation
Real DOM is implemented on the browser.
Virtual DOM is utilized by frameworks and libraries such as React, Vue etc.
Shadow DOM is implemented on the browser.
Principle
The DOM represents the document/webpage as nodes and objects, allowing programming languages like javascript to interact with the page using an API.
The Virtual DOM is a tree representation of the real DOM using nodes and objects and is subsequently used as a blueprint to update the real DOM.
The Shadow DOM doesn’t comprehensively represent the whole DOM. Instead of adding DOM items to the main DOM tree, it inserts subtrees of DOM elements into the document.
Real DOM Vs Virtual DOM Vs Shadow DOM
Conclusion
In this note series, we understood about Real DOM, Virtual DOM and Shadow DOM differences and usages in JavaScript Frameworks. We also understood the DOM principles about Real DOM, Virtual DOM and Shadow DOM.
Thanks for reading! I hope you enjoyed and learned about the Real DOM Vs Virtual DOM Vs Shadow DOM In JavaScript Frameworks. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Service vs IntentService In Android).
In this note series, we will understand the differences between the Service and IntentService in Android.
So Let’s begin.
Service
Service is an android component that is used to perform some long-running operations in the background, such as in the Music app, where we run the app in the background while using other mobile apps at the same time. The best part is that we don’t need to provide some UI for the operations to be performed in the background. By using Service, we can perform some InterProcess Communication(IPC) also. So, with the help of Service, we can perform a number of operations together because any application component can start a Service and can run in background.
There are three ways of using Service:
1. Foreground Service :
A foreground service is a Service that will let the user know about what is happening in the background. For example, in the Music application, the user can see the ongoing song on the device as a form of notification. So, here displaying notification is a must.
2. Background Service :
Here, the user will never know about what is happening in the background of the application. For example, whatsapp messenger compresses the image file to reduce the size while sending some images over whatsapp. This task is done in background and the user have no idea about what is going in the background. But for the API level 21 or higher, the Android System imposes some restrictions while using the Background Service. So, we take care of those restrictions before using the Background Service.
3. Bound Service :
The Bound Service is used when one or more than one application component binds the Service by using the bindService() method. If the applications unbind the Service, then the Service will be destroyed.
IntentService
The Service is the base class for the IntentService. Basically, it uses “work queue process” pattern where the IntentService handles the on-demand requests (expressed as Intents) of clients. So, whenever a client sends a request then the Service will be started and after handling each and every Intent, the Service will be stopped. Clients can send the request to start a Service by using Context.startService(Intent) . Here, a worker thread is created and all requests are handled using the worker thread but at a time, only one request will be processed.
To use IntentService, we have to extend the IntentService and implement the onHandleIntent(android.content.Intent).
Service vs IntentService
In this section, we will look upon some of the differences between the Service and IntentService, so that it will be easier for us to find which one to use in which condition. Let’s see the difference:
If we want some background task to be performed for a very long period of time, then we should use the IntentService. But at the same time, we should take care that there is no or very less communication with the main thread. If the communication is required then we can use main thread handler or broadcast intents. We can use Service for the tasks that don’t require any UI and also it is not a very long running task.
To start a Service, we need to call the onStartService() method while in order to start IntentService, we have to use Intent i.e. start the IntentService by calling Context.startService(Intent).
Service always runs on the Main thread while the IntentService runs on a separate Worker thread that is triggered from the Main thread.
Service can be triggered from any thread while the IntentService can be triggered only from the Main thread i.e. firstly, the Intent is received on the Main thread and after that, the Worker thread will be executed.
If we are using Service then there are chances that our Main thread will be blocked because Service runs on the Main thread. But, in case of IntentService, there is no involvement of the Main thread. Here, the tasks are performed in the form of Queue i.e. on the First Come First Serve basis.
If we are using Service, then we have to stop the Service after using it otherwise the Service will be there for an infinite period of time i.e. until our phone is in normal state. So, to stop a Service, we have to use stopService() or stopSelf() . But in the case of IntentService, there is no need of stopping the Service because the Service will be automatically stopped once the work is done.
If we are using IntentService, then we will find it difficult to interact with the UI of the application. If we want to out some result of the IntentService in our UI, then we have to take help of some Activity.
Conclusion
In this note series, we understood about Service and IntentService differences and usages in android. We also discussed about fundamental concepts of Service and IntentService. If we have some limited amount of tasks to be performed in the background, then we can use Service, otherwise, we can use IntentService.
Thanks for reading! I hope you enjoyed and learned about Service vs IntentService in Android. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Do And Don’t Valuable Checklist Summary Of React Component Lifecycle Methods).
In this note series, we will learn about the ReactJS Component Lifecycle methods checklist. And, this checklist points us to the principles of each lifecycle component method. So, this article will demonstrate the below React Component Lifecycle Methods checklist :
constructor
render
componentDidMount
componentDidUpdate
shouldComponentUpdate
componentWillUnmount
static getDerivedStateFromError
componentDidCatch
So Let’s begin.
1. constructor
DO
Assign the initial state to this.state directly.
Prepare all class fields and bind functions that will be passed as callbacks.
DON’T
Cause any side effects (AJAX calls, subscriptions etc.)
Call setState()
Copy props into state (only use this pattern if we intentionally want to ignore prop updates).
2. render
DO
Return a valid javascript value.
The render() function should be pure.
DON’T
Call setState()
3. componentDidMount
DO
Set up subscriptions
Network requests
May setState() immediately (Use this pattern with caution, because It often causes performance issues).
DON’T
Call this.setState as it will result in a re-render.
4. componentDidUpdate
DO
Network requests Incase if the props have changed otherwise not required.
May call setState() immediately in componentDidUpdate() ,but it must be wrapped in a condition.
DON’T
Call this.setState as it will result in a re-render.
5. shouldComponentUpdate
DO
Use to increase performance of components.
DON’T
Cause any side effects (AJAX calls etc.)
Call this.setState
6. componentWillUnmount
DO
Remove any timers or listeners created in the life span of the component.
DON’T
Call this.setState, start new listeners or timers.
7. static getDerivedStateFromError
DO
Catch errors and return them as state objects.
Handle fallback rendering.
DON’T
Cause any side effects
8. componentDidCatch
DO
Side effects are permitted
Log errors
DON’T
Render a fallback UI with componentDidCatch() by calling setState.
Conclusion
In this note series, We understood about DO and DON’T checklist of the ReactJS lifecycle methods.
Thanks for reading! I hope you enjoyed and learned about DO and DON’T checklist of the React lifecycle methods. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (iOS Best Practices And Swift Coding Standards With Code Organization, Spacing and Comments).
In this note series, we will learn about iOS Best Practices and Swift Coding Standards With Code Organization, Spacing and Comments. Coding standards act as a guideline for ensuring quality and continuity in iOS code. We will discuss about iOS best practices and swift coding standards with Code Organization, Spacing and Comments which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.
So Let’s begin.
Code Organization
We can use extensions to organize our code into logical blocks of functionality. Each extension should be set off with a // MARK: – comment to keep things organised.
Protocol Conformance
We can prefer adding a separate extension for the protocol methods when adding protocol conformance to a model. This keeps the related methods grouped together with the protocol and can simplify instructions to add a protocol to a class with its associated methods.
Preferred :
class MyViewController: UIViewController {
// class stuff here
}
// MARK: - UITableViewDataSource
extension MyViewController: UITableViewDataSource {
// table view data source methods
}
// MARK: - UIScrollViewDelegate
extension MyViewController: UIScrollViewDelegate {
// scroll view delegate methods
}
Not Preferred :
class MyViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate {
// all methods
}
Since the compiler does not allow us to re-declare protocol conformance in a derived class, it is not always required to replicate the extension groups of the base class.
This is especially true if the derived class is a terminal class and a small number of methods are being overridden. When to preserve the extension groups is left to the discretion of the developer.
For UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions.
Unused Code
Unused (dead) code, including Xcode template code and placeholder comments should be removed. An exception is when our tutorial or book instructs the user to use the commented code.
Aspirational methods not directly associated with the article whose implementation simply calls the superclass should also be removed. This includes any empty/unused UIApplicationDelegate methods.
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return Database.contacts.count
}
Minimal Imports
Import only the modules a source file requires. For example, don’t import UIKit when importing Foundation will suffice. Likewise, don’t import Foundation if we must import UIKit.
Preferred:
//1
import UIKit
var view: UIView
var deviceModels: [String]
//2
import Foundation
var deviceModels: [String]
Not Preferred:
//1
import UIKit
import Foundation
var view: UIView
var deviceModels: [String]
//2
import UIKit
var deviceModels: [String]
Spacing
Indent using 2 spaces rather than tabs to conserve space and help prevent line wrapping. Be sure to set this preference in Xcode and in the Project settings as shown below:
Method braces and other braces (if/else/switch/while etc.) always open on the same line as the statement but close on a new line.
There should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means we should refactor into several methods.
There should be no blank lines after an opening brace or before a closing brace.
Colons always have no space on the left and one space on the right. Exceptions are the ternary operator ? :, empty dictionary [:] and #selector syntax addTarget(_:action:).
Long lines should be wrapped at around 70 characters. A hard limit is intentionally not specified.
Avoid trailing whitespaces at the ends of lines.
Add a single newline character at the end of each file.
We can re-indent by selecting some code (or Command-A to select all) and then Control-I (or Editor ▸ Structure ▸ Re-Indent in the menu). Some of the Xcode template code will have 4-space tabs hard coded, so this is a good way to fix that.
Preferred:
//1
if user.isHappy {
// Do something
} else {
// Do something else
}
//2
class TestDatabase: Database {
var data: [String: CGFloat] = ["A": 1.2, "B": 3.2]
}
Not Preferred:
//1
if user.isHappy
{
// Do something
}
else {
// Do something else
}
//2
class TestDatabase : Database {
var data :[String:CGFloat] = ["A" : 1.2, "B":3.2]
}
Comments
When we are needed, we can use comments to explain why a particular piece of code does something. Comments must be kept up-to-date or deleted.
We should avoid block comments inline with code, as the code should be as self-documenting as possible.
Exception: This does not apply to those comments used to generate documentation.
We should also avoid the use of C-style comments (/* … */). We can prefer the use of double- or triple-slash.
Conclusion
In this note series, we understood about iOS Best Practices and Swift Coding Standards With Code Organization, Spacing and Comments. We discussed about iOS Swift based Code Organization, Spacing and Comments concepts which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.
Thanks for reading! I hope you enjoyed and learned about Code Organization, Spacing and Comments concepts in iOS Swift. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (iOS Best Practices And Swift Coding Standards With Naming Conventions).
In this note series, we will learn about iOS Best Practices and Swift Coding Standards With Naming Conventions. Coding standards act as a guideline for ensuring quality and continuity in iOS code. We will discuss about iOS best practices and swift coding standards with Naming Conventions which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.
So Let’s begin.
Overview of Naming Conventions
Descriptive and consistent naming makes code easier to read and understand. We can use the swift naming conventions described in the API Design Guidelines. Some key takeaways include:
Striving for clarity at the call site
Prioritizing clarity over brevity
Using camel case (not snake case)
Using uppercase for types (and protocols), lowercase for everything else
Including all needed words while omitting needless words
Using names based on roles, not types
Sometimes compensating for weak type information
Striving for fluent usage
Beginning factory methods with make
Naming methods for their side effects
Verb methods follow the -ed, -ing rule for the non-mutating version
Noun methods follow the formX rule for the mutating version
Boolean types should read like assertions
Protocols that describe what something is should read as nouns
Protocols that describe a capability should end in -able or -ible
Using terms that don’t surprise experts or confuse beginners
Generally avoiding abbreviations
Using precedent for names
Preferring methods and properties to free functions
Casing acronyms and initialisms uniformly up or down
Giving the same base name to methods that share the same meaning
Avoiding overloads on return type
Choosing good parameter names that serve as documentation
Preferring to name the first parameter instead of including its name in the method name, except as mentioned under Delegates
Labeling closure and tuple parameters
Taking advantage of default parameters
Prose
When we refer methods in prose, being unambiguous is critical. We can refer method name in the simplest form as possible.
Write method name with no parameters. Example: Next, we need to call addTarget.
Write method name with argument labels. Example: Next, we need to call addTarget(_:action:).
Write the full method name with argument labels and types. Example: Next, we need to call addTarget(_Any?,action:Selector?).
For example using UIGestureRecognizer, Write method name with no parameter is unambiguous and preferred. We can use Xcode’s jump bar to lookup methods with argument labels. We can put the cursor in the method name and press Shift-Control-Option-Command-C (all 4 modifier keys) and Xcode will kindly put the signature on our clipboard.
Delegates
When we create custom delegate methods, an unnamed first parameter should be the delegated source. UIkit contains numerous examples of custom delegates methods.
We can use compiler inferred context to write shorter, clear code.
Preferred:
let selector = #selector(viewDidLoad)
view.backgroundColor = .red
let toView = context.view(forKey: .to)
let view = UIView(frame: .zero)
Not Preferred:
let selector = #selector(ViewController.viewDidLoad)
view.backgroundColor = UIColor.red
let toView = context.view(forKey: UITransitionContextViewKey.to)
let view = UIView(frame: CGRect.zero)
Generics
Generic type parameters should be descriptive, upper camel case names. When a type name doesn’t have a meaningful relationship or role, use a traditional single uppercase letter such as T, U, or V.
Swift types are automatically namespaced by the module that contains them and we should not add a class prefix such as RW.
If two names from different modules collide, we can disambiguate by prefixing the type name with the module name. However, we can only specify the module name when there is possibility for confusion which should be rare.
import SomeModule
let myClass = MyModule.UsefulClass()
Language
We can use US English spelling to match Apple’s API.
Preferred:
let color = “red”
Not Preferred:
let colour = “red”
Conclusion
In this note series, we understood about iOS Best Practices and Swift Coding Standards With Naming Conventions. We discussed about Naming Conventions which will helps to ensure our code as efficient, error-free, simple ,easy maintenance enabled and bug rectification.
Thanks for reading! I hope you enjoyed and learned about Naming Conventions concepts in iOS. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (An Overview Of Functions Currying In Kotlin).
In this note series, We will understand about Functions Currying in Kotlin. Currying is a common technique in functional programming. It allows transforming a given function that takes multiple arguments into a sequence of functions, each having a single argument.
In this short note series, we are going to implement an automatic currying mechanism that could be applied to any function taking three parameters.
So Let’s begin.
Overview
We can understand Currying as :
A common technique in functional programming.
Transforming a given function that takes multiple arguments into a sequence of functions, each having a single argument.
Each of the resulting functions handles one argument of the original (uncurried) function and returns another function.
To understand the concept of functions currying, let’s consider the following example of a function handling three parameters:
fun foo(a: A, b: B, c: C): D
Its curried form would like this :
fun carriedFoo(a: A): (B) -> (C) -> D
In other words, the curried form of the foo function would take a single argument of the A type and return another function of the following type: (B) -> (C) -> D. The returned function is responsible for handling the second argument of the original function and returns another function, which takes the third argument and returns a value of type D.
How To Implement it ?
In this section, we are going to implement the curried() extension function for the generic functional type declared as follows: ((P1, P2, P3). The curried() function is going to return a chain of single-argument functions and will be applicable to any function which takes three arguments.
Here, we can implement Functions Currying with the below steps :
Step 1 –Declare a header of the curried() function :
Let’s explore how to use the curried() function in action. In the following example, we are going to call curried() on the following function instance which is responsible for computing a sum of three integers:
fun sum(a: Int, b: Int, c: Int): Int = a + b + c
In order to obtain a curried form of the sum() function, we have to invoke the curried() function on its reference:
::sum.curried()
Then we can invoke the curried sum function in the following way:
val result: Int = ::sum.curried()(1)(2)(3)
Here, the result variable is going to be assigned an integer value equal to 6.
In order to invoke the curried() extension function, we access the sum() function reference using the :: modifier. Then we invoke the next functions from the function sequence returned by the curried function one by one.
The preceding code could be written in an equivalent more verbose form with explicit types declarations:
val sum3: (a: Int) -> (b: Int) -> (c: Int) -> Int = ::sum.curried()
val sum2: (b: Int) -> (c: Int) -> Int = sum3(1)
val sum1: (c: Int) -> Int = sum2(2)
val result: Int = sum1(3)
Under the hood, the currying mechanism implementation is just returning functions nested inside each other. Every time the specific function is invoked, it returns another function with the arity reduced by one.
Conclusion
In this note series, we understood about Functions Currying in Kotlin. Currying is useful whenever we can’t provide the full number of required arguments to the function in the current scope. We can apply only the available ones to the function and return the transformed function.
Thanks for reading! I hope you enjoyed and learned about Functions Currying in Kotlin. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (How To Disable Screen Rotation In React Native).
In this note series, we will learn how to Disable Screen Rotation In React Native. Handheld mobile devices always have two orientation mode Portrait mode and Landscape mode because of their design to hold in the hand. Portrait mode is by default mode in mobile devices, and if we rotate the device, it turns into Landscape mode.
So Let’s begin.
For Android Devices
Open Project -> android -> app -> src -> main ->AndroidManifest.xml .
Now, we have to put android:screenOrientation=“portrait” in AndroidManifest file.
After changing AndroidManifest.xml file, we need to re-run our project. This would disable the landscape mode in our current application in android devices.
For iOS Devices
Open Project ->ios -> Project_Name.xcodeproj file in XCode.
After opening the project in XCode, select project name.
Now Goto -> General -> Deployment Info and only select the Portrait mode.
Now Re-run our project. This would disable the landscape mode in our current application in iOS devices.
Conclusion
In this note series, we understood how to Disable Screen Rotation in React Native. This article showed the Disable Screen Rotation Steps in React Native.
Thanks for reading ! I hope you enjoyed and learned about Disable Screen Rotation Concepts in React Native. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (How To Debug HTTPS Problems With CFNetwork Diagnostic Logging In iOS ?).
In this note series, we will understand how to use CFNetwork diagnostic logging to investigate HTTP and HTTPS problems in iOS.
So Let’s begin.
Overview
If we’re using URLSession and need to debug a complex networking issue, we can enable CFNetwork diagnostic logging to get detailed information about the progress of our network requests. CFNetwork diagnostic logging has unique advantages relative to other network debugging tools, including:
Minimal setup
The ability to look at network traffic that’s protected by Transport Layer Security (TLS).
Information about CFNetwork’s internal state, like which cookies get saved and applied.
CFNetwork diagnostic logging is not exclusive to the CFNetwork framework. The core implementation of the URLSession API lives within the CFNetwork framework, and thus we can and should use CFNetwork diagnostic logging if we’re using URLSession.
Understand the Security Implications
CFNetwork diagnostic logs may contain decrypted TLS data and other security-sensitive information. Take these precautions:
Restrict access to any logs we capture.
If we build an app that enables this logging programmatically, make sure that anyone who receives that app understands the security implications of using it.
If we send a log to Apple, redact any security-sensitive information.
CFNetwork diagnostic logs may contain information that is extremely security-sensitive. Protect these logs accordingly.
Enable Logging In Xcode
To enable CFNetwork diagnostic logging, edit the current scheme (choose Product > Scheme > Edit Scheme), navigate to the Arguments tab, and add a CFNETWORK_DIAGNOSTICS item to the Environment Variables list. The value of this item can range from 0 to 3, where 0 turns logging off, and higher numbers give us progressively more logging. When we next run our app and use URLSession, CFNetwork diagnostic log entries appear in Xcode’s debug console area. If the console area isn’t visible, choose View > Debug Area > Show Debug Area to show it.
Enable Logging Programmatically
To investigate problems outside of Xcode, programmatically enable CFNetwork diagnostic logging by setting the environment variable directly.
setenv("CFNETWORK_DIAGNOSTICS", "3", 1)
Do this right at the beginning of the app’s launch sequence:
If we’re programming in Objective-C, put the code at the start of our main function.
If our program has a C++ component, make sure this code runs before any C++ static initializers that use CFNetwork or any APIs, like URLSession, that use CFNetwork.
If we’re programming in Swift, put this code in main.swift. By default, Swift apps don’t have a main.swift. We need to add one.
View Log Entries
How we view the resulting log entries depends on our specific situation:
In macOS, if we can reproduce the problem locally, run the Console utility on our Mac and view log entries there.
In iOS, if we can reproduce the problem locally, and we’re able to connect the device to our Mac through USB, run the Console utility on our Mac and view log entries there. Make sure we select our iOS device from the source list on the left of the main Console window (choose View > Show Sources if the source list is not visible).
If neither of the above work for us — for example, if we’re trying to debug a problem that can only be reproduced by one of our users in the field — get a sys-diagnose log from the machine exhibiting the problem and then extract the log entries from that.
Conclusion
In this note series, we understood How to use CFNetwork diagnostic logging to investigate HTTP and HTTPS problems in iOS.
Thanks for reading! I hope you enjoyed and learned about CFNetwork diagnostic logging usage in iOS. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (How To Debug HTTP Server-Side Errors In iOS ?).
In this note series, we will understand HTTP server-side errors and how to debug them in iOS.
So Let’s begin.
Overview
Apple’s HTTP APIs report transport errors and server-side errors:
A transport error is caused by a problem getting our request to, or getting the response from, the server. These are represented by a NSError value, typically passed to our completion handler block or to a delegate method like urlSession(_:task:didCompleteWithError:). If we get a transport error, investigate what’s happening with our network traffic.
A server-side error is caused by problems detected by the server. Such errors are represented by the statusCode property of the HTTPURLResponse.
The status codes returned by the server aren’t always easy to interpret. Many HTTP server-side errors don’t give us a way to determine, from the client side, what went wrong. These include the 5xx errors (like 500 Internal Server Error) and many 4xx errors (for example, with 400 Bad Request, it’s hard to know exactly why the server considers the request bad).
Print the HTTP Response Body
In this section, we explain how to debug these server-side problems.
Sometimes, the error response from the server includes an HTTP response body that explains what the problem is. Look at the HTTP response body to see whether such an explanation is present. If it is, that’s the easiest way to figure out what went wrong. For example, consider this standard URLSession request code.
URLSession.shared.dataTask(with: url) { (responseBody, response, error) in
if let error = error {
// handle transport error
}
let response = response as! HTTPURLResponse
let responseBody = responseBody!
if !(200...299).contains(response.statusCode) {
// handle HTTP server-side error
}
// handle success
print("success")
}.resume()
A server-side error runs the line labeled handle HTTP server-side error. To see if the server’s response contains any helpful hints what went wrong, add some code that prints the HTTP response body.
// handle HTTP server-side error
if let responseString = String(bytes: responseBody, encoding: .utf8) {
// The response body seems to be a valid UTF-8 string, so print that.
print(responseString)
} else {
// Otherwise print a hex dump of the body.
print(responseBody as NSData)
}
Compare Against a Working Client
If the HTTP response body doesn’t help, compare our request to a request issued by a working client. For example, the server might not fail if we send it the same request from:
A web browser, like Safari
A command-line tool, like curl
An app running on a different platform
If we have a working client, it’s relatively straightforward to debug our problem:
Use the same network debugging tool to record the requests made by our client and the working client. If we’re using HTTP (not HTTPS), use a low-level packet trace tool to record these requests. If we’re using HTTPS, with Transport Layer Security (TLS), we can’t see the HTTP request. In that case, if our server has a debugging mode that lets us see the plaintext request, look there. If not, a debugging HTTP proxy may let us see the request.
Compare the two requests. Focus on the most significant values first.
Do the URL paths or the HTTP methods match?
Do the Content-Type headers match?
What about the remaining headers?
Do the request bodies match?
If these all match and things still don’t work, we may need to look at more obscure values, like the HTTP transfer encoding and, if we’re using HTTPS, various TLS parameters.
Address any discrepancies.
Retry with our updated client.
If things still fail, go back to step 1.
Debug on the Server
If we don’t have access to a working client, or we can’t get things to work using the steps described in the previous section, our only remaining option is to debug the problem on the server. Ideally, the server will have documented debugging options that offer more insight into the failure. If not, escalate the problem through the support channel associated with our server software.
Conclusion
In this note series, we understood HTTP server-side errors and how to debug them in iOS.
Thanks for reading! I hope you enjoyed and learned about HTTP Server-side Concept in iOS. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series (Choosing Network Debugging Tool In iOS).
In this note series, we will understand which tool works best for our network debugging problem in iOS.
So Let’s begin.
Overview
Debugging network problems is challenging because of the fundamental nature of networking. Networking is asynchronous, time-sensitive, and error prone. The two programs involved (the client and the server, say) are often created by different developers, who disagree on the exact format of the data being exchanged. Fortunately, a variety of tools can help us debug such problems.
A key goal of these tools is to divide the problem in two. For example, if we’re working on a network client that sends a request to a server and then gets an error back from that server, it’s important to know whether things failed because the request was incorrect (a problem with our client) or because the server is misbehaving. We can use these network debugging tools to view the traffic going over the network, and thus independently check the validity of that traffic.
Choosing Best Network Debugging Tool
The best tool to use depends on the APIs we’re using and the problems we’ve encountered:
We may find that our request makes it to the server and then the server sends us a response showing that it failed If we are working at the HTTP level (for example, we get an HTTP response with a status code of 500 Internal Server Error).
If we’re using URLSession, or one subsystem that uses URLSession internally, we can enable CFNetwork diagnostic logging to get a detailed view of how our requests were processed.
We need a packet trace if we want a low-level view of the traffic exchanged over the network,.
If we’re working in Safari or one of the various web views (like WKWebView), we can use the Web Inspector to view the network requests issued by the page.
Some of the most popular network debugging tools, like HTTP debugging proxies, are third-party products.
Conclusion
In this note series, we understood which tool works best for your network debugging problem in iOS.
Thanks for reading! I hope you enjoyed and learned about Choosing Best Network Tool Concept in iOS. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :