<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sam Wang on Medium]]></title>
        <description><![CDATA[Stories by Sam Wang on Medium]]></description>
        <link>https://medium.com/@0723Sam?source=rss-b8f85c66ee49------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y7vA_riEgzmTBK_ze4Qk8A@2x.jpeg</url>
            <title>Stories by Sam Wang on Medium</title>
            <link>https://medium.com/@0723Sam?source=rss-b8f85c66ee49------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 12:02:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@0723Sam/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How did we fine-tune the Go application performance]]></title>
            <link>https://medium.com/honestbee-tw-engineer/how-did-we-fine-tune-the-go-application-performance-76f3a6f77736?source=rss-b8f85c66ee49------2</link>
            <guid isPermaLink="false">https://medium.com/p/76f3a6f77736</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[new-relic]]></category>
            <category><![CDATA[elasticache]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Sam Wang]]></dc:creator>
            <pubDate>Fri, 29 Mar 2019 10:43:34 GMT</pubDate>
            <atom:updated>2019-03-30T04:29:14.193Z</atom:updated>
            <content:encoded><![CDATA[<p>Before the article start, I want to announce that honestbee just open sourced our golang worker-pool library <a href="https://github.com/honestbee/jobq"><strong><em>jobq</em></strong></a>, it’s a very easy-to-use library and can save your time on maintaining the goroutine and channel usage, feel free to comment, reporting issues and contribute to making it better :)</p><h3>The increased response time</h3><p>In honestbee app usage, one of the important part is the address search, because it’s the entry point of using our services. In order to create more flexibility and convenience, we built a service called “Atlas” to become a delegation server with postal code search and Google maps api call.</p><p>Recently we found the response time increased around 100ms after modified some code based on new Google Place Autocomplete policy to use <strong><em>session_token</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*J_LRlKRNVgJQhYkEvM5b5g.png" /><figcaption>Average response time increased 100ms more</figcaption></figure><p>Then, based on the usual behavior, the first response is to check what did we do wrong on the code modification, and the suspected point is definitely on the <em>session_token</em> adding, because it’s generating based on each api call to Atlas and the token itself is a UUID created via Random, and On Unix-like systems, Random Reader reads from <em>/dev/urandom</em> and performs I/O actions.</p><h3>Is that the root cause?</h3><p>Performance issue solving always like a crime scene investigation and you always need to dig out more, and we found it’s <strong>actually not</strong> causing via UUID generate because it’s only using extra 300 nanoseconds and very little of the memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*U_tC5FVxULzRXKTRsVqyCg.png" /><figcaption>GC pause time increased</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*LR0YyCAbYWySQCBXpoMBxw.png" /><figcaption>GC pause fraction raised</figcaption></figure><p>Based on the above abnormal GC pause graph, we can sure it’s because of the memory being stuck for a longer period and the original GC cycle cannot handle it anymore, it’s very obvious from below newRelic graph (Yellow part).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*2ToahAT7PNnEHo67grjC8w.png" /><figcaption>Redis response latency increased</figcaption></figure><p>and we go check on AWS elastic-cache, indeed, the Swap usage raised to almost 1.5GB lol, that’s because of lacking the physical memory so system decided to use Swap to cover.</p><h3>The Recovery</h3><p>We decided to increase the memory size from <strong><em>cache.t2.small</em></strong> to <strong><em>cache.m1.medium</em></strong>, also adjust the<em> GOGC </em>percentage <strong>from 100 to 400</strong> because during this period of time honestbee also enabled the capability of SG search using text-based content and JP postal code search to improve accuracy, that also increased the traffic (throughput).</p><blockquote>The GOGC variable sets the initial garbage collection target percentage. A collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. The default is GOGC=100. Setting GOGC=off disables the garbage collector entirely. The runtime/debug package’s SetGCPercent function allows changing this percentage at run time. See <a href="https://golang.org/pkg/runtime/debug/#SetGCPercent">https://golang.org/pkg/runtime/debug/#SetGCPercent</a>.</blockquote><p>It worked!! and the SLA also back to normal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*OrtoAqnIU86Lgv7VXpuw4A.png" /><figcaption>Response time recovered</figcaption></figure><h3>Is it the end of the story?</h3><p>No, because we still can observe the long latency of Web external (Google maps api), after searching in the code base, previously the engineers using for loop to call google api and complete the full results, it means that one of the searches needs to call 1 AutoComplete request and based on the predictions to get the detail lat/long and postal code from Geocoding api, like A+B+C.</p><p>To solve it is actually quite simple, which is make concurrent can happen on the search result gathering, this is the time that <a href="https://github.com/honestbee/jobq">jobq</a> comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*I3GIAzq64mOc5_xgihJdng.png" /><figcaption>Setup the dispatcher with limited size</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGv4iiJ5BpTqj-y-nj_Krg.png" /><figcaption>Using jobs to handle the first level of the different type of address querying</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZHziY-GVeLdCutTg2kV3A.png" /><figcaption>The second level of the prediction geocoding reverse</figcaption></figure><p>The reason we not using dynamic adjust on jobq dispatcher is because of the job will also trigger I/O (postgres &amp; redis), increase automatically may cause fd running out issue and lead to panic.</p><p>After this approach, we successfully reduced from A+B+C time to a more flatten response time (depends on the latency of A or B or C) and saves around 1/3 response latency time.</p><h3>Conclusion</h3><p>Monitoring the performance is both interesting and tough, but once if you can solve it, you will learn a lot from the experience, I did, this week.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76f3a6f77736" width="1" height="1" alt=""><hr><p><a href="https://medium.com/honestbee-tw-engineer/how-did-we-fine-tune-the-go-application-performance-76f3a6f77736">How did we fine-tune the Go application performance</a> was originally published in <a href="https://medium.com/honestbee-tw-engineer">honestbee-tw-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Kubernetes cluster and deploy drone on AWS — Part II]]></title>
            <link>https://medium.com/honestbee-tw-engineer/setup-kubernetes-cluster-and-deploy-drone-on-aws-part-ii-c7b4a5e3f184?source=rss-b8f85c66ee49------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7b4a5e3f184</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[drone-service]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sam Wang]]></dc:creator>
            <pubDate>Fri, 21 Dec 2018 04:26:22 GMT</pubDate>
            <atom:updated>2018-12-21T04:26:22.600Z</atom:updated>
            <content:encoded><![CDATA[<h3>Setup Kubernetes cluster and deploy drone on AWS — Part II</h3><p>In the previous Part I <a href="https://medium.com/honestbee-tw-engineer/setup-kubernetes-cluster-and-deploy-drone-on-aws-part-i-89d36cb6f88b?fbclid=IwAR3xMWfKLO0QF9opExnICGVmyvuz0YwCTfRxOGx7KdoHgRwU9JgGKY_cnvs">article</a>, we already introduced how to set up a Kubernetes cluster on AWS, now, it’s time to deploy Drone service into it.</p><h3>Why Drone?</h3><p>People may ask why not using Jenkins to build the CI/CD process, the reason why we choose Drone is that it can use the <strong>container</strong> concept, and everything can be a container (except running Xcode UI testing). If you are not familiar with what is docker, can refer <a href="https://www.docker.com/why-docker">here</a>. Jenkins requires difficult project settings and hard to extend the components if not having any Java developer in your team, that’s why we prefer using Drone to be our CI/CD tool.</p><p>Before docker announced, we usually need to establish multiple different services and deploy them one by one, the management cost also very high and the learning curve is steep, with <strong><em>docker</em></strong> and <strong><em>docker-compose</em></strong>, we can draw a map between services easily and deploy them in a few simple steps, team can be more focusing on writing business logic instead of stuck on DevOps.</p><p>Also, with <a href="https://hub.docker.com/">docker-hub</a>, it makes easier to get the open sourced contributed images to use. For example, if I want to deploy a Redis image to the cluster, I can just write:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ff84754fbbd817a7e7807ea078b1e4b/href">https://medium.com/media/3ff84754fbbd817a7e7807ea078b1e4b/href</a></iframe><p><em>redis:alpine</em> is actually helping you to pull the Redis image from docker hub <a href="https://hub.docker.com/_/redis/">repository</a></p><h3>Setup deployment.yml file</h3><p>Having deployment.yml means you can use <strong><em>kubectl</em></strong> to create pods on the cluster, Drone’s architecture requires one server and multiple agents, we need to set up these within the development.yml to have <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">deployment controllers</a>.</p><h4>Isolating pods under a namespace</h4><p>When we set up namespace on Kubernetes cluster, the benefit is to isolate the pods under this namespace and will not be affected by other areas, also it can be easier to view and maintain the relevant deployment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc54aa5514113a93ec966792bb8bcb9e/href">https://medium.com/media/cc54aa5514113a93ec966792bb8bcb9e/href</a></iframe><p>You can use <em>kubectl create -f namespace.yml</em> to generate the namespace.</p><p>Or, you can type in the console as well <em>kubectl create namespace drone</em> , then check if the namespace is created, after namespace created, we will set all the deployment under namespace: drone</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*rtVwnRq4bu5JtMYBC9Bfyw.png" /></figure><h4>The secret key to communicate between drone server and agent</h4><p>In order to communicate between drone server and agent, we will need to generate a secret key</p><p><em>echo -n &#39;your key here&#39; | base64</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32bebbe6078260be60e6ecb5452c53e3/href">https://medium.com/media/32bebbe6078260be60e6ecb5452c53e3/href</a></iframe><p><em>kubectl create -f secret.yml</em></p><h4>Setup config map</h4><p>Before writing deployment, it will be better if we can separate the config map file into a standalone yaml for a clear view.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f43bd21f378f79f57db9664c58dc8222/href">https://medium.com/media/f43bd21f378f79f57db9664c58dc8222/href</a></iframe><p>Noted on the github settings, since our drone will connect with github for any push, pull request build, we have to create an OAuth app under developer settings first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TnuYt2mb85kf9h-dAWKeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*-yeWqogJqQeMyB2ESoHLqQ.png" /></figure><p>Set the Homepage URL to your host, and fulfill the Authorization callback URL with http(s)://host/authorize , after save, you should see <strong><em>Client ID &amp; Client Secret</em></strong>, copy those to your config map yaml file.</p><h4>The Deployment</h4><p>Below are the complete deployment files, please aware that under volumes node we need to setup the AWS EBS volumeID, you can create a volume using aws command line tool.</p><pre><em>aws ec2 create-volume --availability-zone=ap-southeast-1a --size=10 --volume-type=gp2</em></pre><p>After executing, you can search forvol-xxxxx in your console, copy and paste into the development yaml volumeID.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a7d73a5ecd65c5d6ace0f5d137f71fe/href">https://medium.com/media/1a7d73a5ecd65c5d6ace0f5d137f71fe/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3ff37aee9bc37749beb8f4ce0935c26/href">https://medium.com/media/f3ff37aee9bc37749beb8f4ce0935c26/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3ff37aee9bc37749beb8f4ce0935c26/href">https://medium.com/media/f3ff37aee9bc37749beb8f4ce0935c26/href</a></iframe><h4>Service definition</h4><p>The service definition yaml described how AWS will set up the loading balancer and the annotations can set the ssl certificate id.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b255134df1817e1c284f7735dab1ec14/href">https://medium.com/media/b255134df1817e1c284f7735dab1ec14/href</a></iframe><h3>Final step</h3><p>After all these yaml files, now it’s time to deploy the drone service onto AWS Kubernetes cluster.</p><pre><em>$ kubectl create -f drone-namespace.yaml<br>$ kubectl create -f drone-secret.yaml<br>$ kubectl create -f drone-configmap.yaml<br>$ kubectl create -f drone-server-deployment.yaml<br>$ kubectl create -f drone-server-service.yaml<br>$ kubectl create -f drone-agent-deployment.yaml</em></pre><p>You can check if the service is up <em>kubectl --namespace=drone get service -o wide</em></p><p>And you can even check your pods has been created successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTXpQoSSbRj1U1EhgVo8rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*ikscq5XbKoHvtILOx9ug_Q.png" /></figure><h3>Wanna Rollback?</h3><p>Since we deploy the service under drone namespace, so the deletion is really easy by using <em>kubectl delete -f drone-namespace.yaml</em></p><h3>References</h3><p><a href="https://github.com/appleboy/drone-on-kubernetes/blob/master/aws/README.md"><em>https://github.com/appleboy/drone-on-kubernetes/blob/master/aws/README.md</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7b4a5e3f184" width="1" height="1" alt=""><hr><p><a href="https://medium.com/honestbee-tw-engineer/setup-kubernetes-cluster-and-deploy-drone-on-aws-part-ii-c7b4a5e3f184">Setup Kubernetes cluster and deploy drone on AWS — Part II</a> was originally published in <a href="https://medium.com/honestbee-tw-engineer">honestbee-tw-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Kubernetes cluster and deploy drone on AWS — Part I]]></title>
            <link>https://medium.com/honestbee-tw-engineer/setup-kubernetes-cluster-and-deploy-drone-on-aws-part-i-89d36cb6f88b?source=rss-b8f85c66ee49------2</link>
            <guid isPermaLink="false">https://medium.com/p/89d36cb6f88b</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Sam Wang]]></dc:creator>
            <pubDate>Mon, 03 Dec 2018 06:00:22 GMT</pubDate>
            <atom:updated>2018-12-21T04:27:13.923Z</atom:updated>
            <content:encoded><![CDATA[<h3>Setup Kubernetes cluster and deploy drone on AWS — Part I</h3><p>Before we talking about what is Kubernetes, let’s talk first on the <strong>Monolithic Architecture</strong> and <strong>Microservices</strong>. In the past, what engineers are familiar with usually follows the monolithic architecture, monolithic means composed all in one piece, build a single backend codebase, inject business logic and components within, when company scope becomes bigger and want to scale, we increase more backend service.</p><h3>What’s wrong with that?</h3><p>No, it’s not about right or wrong, using monolithic architecture still can establish your business, just that the scaling strategy will be a bit difficult to maintain, also it increased the complexity of engineers development.</p><p>Back to 2016, when <a href="https://www.honestbee.sg/"><strong>honestbee</strong></a> only have Groceries vertical, our Rails backed backend codebase is quite clean and can be easily maintained, but when things coming to 2017, Laundry and Food vertical came in and introduced more different business logic on Brand / Store / Zone / Order / Fulfillment handling, we starting to add different logic to the original codebase, using state machine to deal with multiple statuses, more design pattern to handles the serializer, polymorphic, etc.</p><h4>Things are getting worse</h4><p>From the business perspective, we can edit the existing backend codebase to achieve the targets and we did, but, from an engineering management perspective, more things get affected.</p><ol><li>The entire backend development progress and performance getting slower from time to time</li><li>New engineer on-boarding speed slow down, people are getting confused and takes a longer time to understand such large codebase with complex business logic</li><li>Hard for debugging, we need to trace more than 3-tiers to deep dive to the root cause.</li><li>Setup multiple instances to serve all countries, but new launched cities stability may get affected by another huge traffic cities.</li></ol><p>Team morale also damaged because of this, because engineers cannot contribute using fast speed as they expected in the beginning, there are too many constraints.</p><h4>How to solve it?</h4><p>Then, we start talking about <a href="https://smartbear.com/learn/api-design/what-are-microservices/">micro-services</a>, but we don’t think micro-service is a silver bullet, we use it to benefit us based on these facts</p><ol><li>Separate services based on different business logic, make the code clean and small, easy to maintain and understand, also faster development</li><li>Deployment is independent and not blocking each other</li><li>Teams can choose their preferred languages and technology, encourage them to discover new tech</li><li>Using different strategy to deploy and scale, regional, domains, etc.</li></ol><p>Of course, some side effects are:</p><ol><li>Deployment management of multiple services (load balancing, scaling, monitoring)</li><li>Partitioning the application and definition into microservices is an art (sometimes we over-engineering)</li><li>Extra effort and monitoring of services communication (e.g. Using message Pub/Sub like Kafka)</li><li>Integration test becomes more complicated</li></ol><p>From our perspective, the Cons &lt; Pros, because the Pros solves the process conflicts, team management difficulties, and the best part is <em>“Teams can choose their preferred languages and technology, encourage them to discover new tech”</em>, it encourages our engineers can feel freer to try &amp; error, which is a good thing for culture.</p><h3>Why Kubernetes?</h3><p>Since we had many micro-services running independently, we definitely don’t want to manually deploy all those containers into each instance, Kubernetes helps us to do the <strong>automatic deployments, expansion, and management</strong>, the benefits are:</p><ol><li>Deploy container to multiple instances at the same time</li><li>Manage container status and doing crash fallback handling, make sure service is alive</li><li>Transfer all containers from instance to instance</li><li>The flexibility of expansion by the k8s cluster</li><li>Open source &amp; active community, backed by Google</li></ol><h3>kops — Kubernetes Operations</h3><p><a href="https://github.com/kubernetes/kops">kops</a> is a component provided from Kubernetes as an operation usage, it can help you to deploy on AWS or GCP.</p><p>First, you will need <strong><em>kubectl</em></strong> toolchain (On mac I’m using <a href="https://docs.brew.sh/Installation">homebrew</a>)</p><p><em>brew install kubernetes-cli</em></p><p>then can check the installation is correct</p><p><em>kubectl version</em></p><p>Once it’s set up, let’s install <strong><em>kops</em></strong></p><p><em>brew update &amp;&amp; brew install kops</em></p><p>After this, you already had kops installed, can type <strong><em>kops</em></strong> in the console and check if the help document shows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iv1aXHbcJYE9mVrsTW_-jA.png" /></figure><h3>AWS Configuration</h3><p>If you don’t have an account yet, please go to <a href="https://aws.amazon.com/console/">AWS Console</a> to signup. AWS has <a href="https://aws.amazon.com/free/">free tier</a> so don’t worry if you just trying to explore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_DI6itJwPinRR8VaWzIGw.png" /></figure><p>And you also need <a href="https://aws.amazon.com/cli/"><strong><em>awscli</em></strong></a> to be installed.</p><p><em>sudo easy_install pip &amp;&amp; pip install awscli</em></p><p>and check the current version with <em>aws --version</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*K1as41igBIHV1oAQaDT_4Q.png" /></figure><p>Now we are going to create a user for kops usage, since we will be using <em>awscli</em> to access the AWS resources, please choose <strong>Programmatic access</strong>, and <strong>Attach existing policies directly</strong>, with<strong> AdministratorAccess</strong>. After user creation completed, copy the value of<strong> Access key ID</strong> &amp; <strong>Secret access key.</strong></p><p>Back to the terminal, type aws configure and set the correct value to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*xUqsK7b5TFxKkSULtLVJDQ.png" /></figure><p>You should be able to find the set values in <em>$HOME/.aws</em></p><p><em>cat ~/.aws/credentials</em></p><h4>S3 bucket</h4><p>Please go to <a href="https://aws.amazon.com/s3">AWS S3</a> to create a bucket for Kubernetes, input the bucket name and assign permission to the account you just created, make sure the region is the same as what you selected on AWS panel. This bucket will store the relevant Kubernetes files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJd3Kpjn8zinORMQFyHG-g.png" /></figure><h4>Route53</h4><p>We will need one domain registered for accessing the Drone service, for detail registration can refer to <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/registrar.html">this</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sKU9Gf_fjW8lgp2f4KF5AQ.png" /></figure><p>Basically, after these, your configuration and preparation on AWS are all done.</p><h3>Establish Kubernetes Cluster</h3><p>Before doing further action for install, we need an SSH key to access for login into Kubernetes Cluster in the future.</p><p>ssh-keygen -f ~/.ssh/id_rsa will save the generated public / private key into the <strong><em>~/.ssh/id_rsa</em></strong>, to check if the key has been generated, type cat ~/.ssh/id_rsa you should see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*xsPUS8jMr3EsZyFlYQ_huA.png" /></figure><h4>Create a cluster</h4><pre><em>kops create cluster \<br>--name=drone.samwang0723.com \<br>--state=s3://k8s-samwang0723 \<br>--zones=ap-southeast-1a \<br>--master-size=t2.micro \<br>--node-size=t2.micro \<br>--node-count=2</em></pre><p><strong>name</strong> — cluster name<br><strong>state</strong> — cluster data storage<br><strong>zone</strong> — AWS node deploy zone<br><strong>master-size</strong> — EC2 <a href="https://aws.amazon.com/ec2/instance-types/">instance type</a> for master<br><strong>node-size</strong> — same as master-size, setup the instance type for nodes<br><strong>node-count </strong>— setup Node count</p><p>After executing the command, you should see the preview of AWS changes, to confirm the update, type below command and kops will perform the change to AWS.</p><p><em>kops update cluster drone.samwang0723.com --yes --state s3://k8s-samwang0723</em></p><p>Now, check your ~/.node/config to see the config of this Kubernetes cluster</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzGEZhX8_9GsAWZJSjA43Q.png" /></figure><p>Remember that <strong><em>username</em></strong> and <strong><em>password</em></strong>, also you will see api server configuration</p><blockquote>server: <a href="https://api.drone.samwang0723.com/"><em>https://api.drone.samwang0723.com</em></a></blockquote><p>Use your account password to login this server URL, it will show all the API usage of Kubernetes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*j4NnczxCzKryBVvz95tThg.png" /></figure><p>Go back to AWS admin panel and check, you will see 3 instances being set up already (1 master 2 nodes)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmpaxJrqTvOiGFcXdHuYZA.png" /></figure><p>Also, Route 53 recordset created as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*LO6x2aeNxv-FBb4Omss9sg.png" /></figure><p>Finally, in your console, check the nodes using <em>kubectl get nodes</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*d3o60_5bERxZaVlUOyNrog.png" /></figure><p>So far, you already have complete cluster established on AWS and you already know that kops really help developers to reduce the painful process while deployment.</p><p>Next, in <a href="https://medium.com/honestbee-tw-engineer/setup-kubernetes-cluster-and-deploy-drone-on-aws-part-ii-c7b4a5e3f184">Part II</a> we will introduce how to deploy <strong><em>Drone</em></strong> to this cluster.</p><p>Side note, if you don’t want to waste money and wanted to delete everything we just setup using kops, you can use:</p><pre><em>kops delete cluster drone.samwang0723.com — state s3://k8s-samwang0723 — yes</em></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89d36cb6f88b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/honestbee-tw-engineer/setup-kubernetes-cluster-and-deploy-drone-on-aws-part-i-89d36cb6f88b">Setup Kubernetes cluster and deploy drone on AWS — Part I</a> was originally published in <a href="https://medium.com/honestbee-tw-engineer">honestbee-tw-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gracefully shutdown in Go http server]]></title>
            <link>https://medium.com/honestbee-tw-engineer/gracefully-shutdown-in-go-http-server-5f5e6b83da5a?source=rss-b8f85c66ee49------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f5e6b83da5a</guid>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Sam Wang]]></dc:creator>
            <pubDate>Tue, 27 Nov 2018 16:40:03 GMT</pubDate>
            <atom:updated>2018-11-27T16:45:41.598Z</atom:updated>
            <content:encoded><![CDATA[<h3>Graceful shutdown in Go http server</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sViCW0A-l6kflwToCR1e8w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/OVbeSXRk_9E?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nikita Kachanovsky</a> on <a href="https://unsplash.com/search/photos/computer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When backend developers writing http servers, the most usual question is:</p><blockquote>how am I being able to terminate all the running processes and make sure resources are released properly?</blockquote><p>Ideally, we should listen (or you can say intercept) for few signals: SIGINT<strong><em>, </em></strong>SIGTERM<strong><em>. </em></strong>Below is the <a href="https://www.win.tue.nl/~aeb/linux/lk/lk-5.html">description</a> of Signals:</p><blockquote>The common communication channel between user space program and kernel is given by the system calls. But there is a different channel, that of the <em>signals</em>, used both between user processes and from kernel to user process.</blockquote><p>What SIGINT means is <em>Signal Interrupted</em>, send when the user types the INTR character (e.g. Ctrl-C).</p><p>The SIGTERM signal is a generic signal used to cause program termination. Unlike SIGKILL, this signal can be blocked, handled, and ignored. It is the normal way to politely ask a program to terminate.</p><p>So usually these 2 signals can cover most of the scenarios while an application needs to be shut down, as long as we can capture the signals, we can handle the rest of the steps (e.g. truncate pending jobs in the queue, etc).</p><h3>Using channel</h3><p>If you familiar with go concurrency, then you will know there is a thing called <strong><em>“Channel”. </em></strong>And one of its biggest advantage and common usage is the blocking behavior, if somewhere you are listening for output from a channel but in the meanwhile that channel not being given any input, the listening place will be blocked until it receives the output.</p><blockquote><em>Channels</em> are the pipes that connect concurrent goroutines. You can send values into channels from one goroutine and receive those values into another goroutine.</blockquote><p>Let’s check the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85b5320a38d4eb6c1a768b0eebc1fe32/href">https://medium.com/media/85b5320a38d4eb6c1a768b0eebc1fe32/href</a></iframe><p>The above code, 1st line in main creates a <em>done</em> channel and it can only accept <em>os.Signal</em> type with 1 capacity, then 2nd line <em>signal.Notify</em> causes the package signal to relay incoming signals to <em>done</em> channel.</p><p>Then,&lt;-done is trying to receive output from <em>done</em> channel, but if we started the application, the “Server Stopped” will not be shown, as described earlier, because if the application running normally without any termination signal intercepted and nothing in the channel, it will be blocked.</p><p>Now you can try Ctrl-C to terminate it, the string will be print out as expected.</p><h3>Handling http requests</h3><p>Now, let’s add the http functionality (with <a href="https://github.com/gorilla/mux">gorilla/mux</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02488a9c1d49dce75d12e06e73612ba8/href">https://medium.com/media/02488a9c1d49dce75d12e06e73612ba8/href</a></iframe><p>As you can see, we created a http endpoint <em>test</em> with the handler, serves on 8080 port, and after the signal listener being set, we start another go-routine to handle the <em>srv.ListenAndServe()</em></p><p>To be honest, it’s not necessary to wrap another go-routine with <em>srv.ListenAndServe()</em> , this method is blocking and in the go documentation it already described that will use separate go-routine for each incoming request. The only reason I’m using go-routine to have another wrapper is because it’s more easier for me to handle the channel interactions and rest of the shutdown steps, if you are interesting with exploring another way to handling it, <a href="https://medium.com/over-engineering/graceful-shutdown-with-go-http-servers-and-kubernetes-rolling-updates-6697e7db17cf">here</a> is the example.</p><blockquote>Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.</blockquote><p>Jump to line 48, we see a <em>srv.Shutdown</em> with <em>Context, </em>this method introduced in <a href="https://golang.org/doc/go1.8#http_shutdown">Go1.8</a>.</p><blockquote><em>Shutdown</em> gracefully shuts down the server without interrupting any active connections. <em>Shutdown</em> works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context’s error, otherwise it returns any error returned from closing the Server’s underlying Listener(s).</blockquote><p>Although Go already had support on it, but it’s still not enough, for 2 parts, internal reason an external reason.</p><h4>Internal Reason</h4><p>The quote above came from Go documentation said <em>“and then waiting </em><strong><em>indefinitely</em></strong><em> for connections to return to idle and then shut down”</em>, this part you should worry because it means some zombie connections may still be there and use your memory, in order to solve this, the safest way is to setup a timeout threshold using the <a href="https://blog.golang.org/context">Context</a>.</p><pre><em>ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)</em></pre><p>The timer context and the cancel function <em>(the cancel function releases its resources)</em> will be returned, and you can use that context to perform <em>Shutdown(ctx) </em>, inside the <em>Shutdown</em> it check if the timer context Done channel is closed and will not run <strong><em>indefinitely.</em></strong></p><h4>External Reason</h4><p>Besides what we’ve explained so far, the major reason of writing graceful shutdown is because in a large system there will not be only 1 http server, usually combines with multiple other connections like database, message queues, etc. And we need to handle these properly as well by defining the defer func and using <em>cancel()</em> to release the resources.</p><pre><em>defer func() {<br>    // Close database, redis, truncate message queues, etc.</em><br>    <em>cancel()<br>}()</em></pre><p>Hope this article can provide you some insights on why we are doing the graceful shutdown. If you have any questions or suggestions, please feel free to contact me!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f5e6b83da5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/honestbee-tw-engineer/gracefully-shutdown-in-go-http-server-5f5e6b83da5a">Gracefully shutdown in Go http server</a> was originally published in <a href="https://medium.com/honestbee-tw-engineer">honestbee-tw-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to prevent using weak self inside swift closure]]></title>
            <link>https://medium.com/swift-programming/how-to-prevent-using-weak-self-inside-swift-closure-2c113b8b2651?source=rss-b8f85c66ee49------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c113b8b2651</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Sam Wang]]></dc:creator>
            <pubDate>Thu, 03 Sep 2015 09:26:32 GMT</pubDate>
            <atom:updated>2015-09-04T11:05:57.521Z</atom:updated>
            <content:encoded><![CDATA[<p>If you had ever written a swift closure, you must have been met the situation about how to prevent self being strong reference inside closure. Usually we force ourselves to use <strong>[weak self]</strong>, and then using <strong>“if let strongSelf = self” </strong>or<strong> “self?.” </strong>to let self can release while dealloc. But it’s really annoying, aren’t them?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*xyn5eKMdwGxW15BqOkHmpQ.png" /><figcaption>old usage of closure</figcaption></figure><p>Swift 1.2 announced a syntax called <strong>“@noescape”</strong>, this attribute indicates that a closure will only live as long as the call so there is no possibility of retain cycles. That means you don’t have to worry about self being retained in closure and makes your code clean &amp; easy-read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*C5WRiI_UregTNhEcNQXDjg.png" /><figcaption>closure use case with @noescape</figcaption></figure><p>Above screenshot presented the case how we use <strong>@noescape</strong>, this example will let swift developers can easily handle the multi-thread access code, and you don’t need to care about the reference problem inside closure because it s lifecycle depends on the call.</p><blockquote>it will not be stored for later execution, such that it is guaranteed not to outlive the lifetime of the call. Function type parameters with the noescape declaration attribute do not require explicit use of self. for properties or methods.</blockquote><p>References:</p><p><a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Attributes.html#//apple_ref/doc/uid/TP40014097-CH35-ID348">https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Attributes.html#//apple_ref/doc/uid/TP40014097-CH35-ID348</a></p><p><a href="http://www.russbishop.net/swift-1-2">http://www.russbishop.net/swift-1-2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c113b8b2651" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-programming/how-to-prevent-using-weak-self-inside-swift-closure-2c113b8b2651">How to prevent using weak self inside swift closure</a> was originally published in <a href="https://medium.com/swift-programming">Swift Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Merge Objective-C static library into Swift (using mosquitto)]]></title>
            <link>https://medium.com/swift-programming/merge-objective-c-static-library-into-swift-using-mosquitto-87ce0b6ec513?source=rss-b8f85c66ee49------2</link>
            <guid isPermaLink="false">https://medium.com/p/87ce0b6ec513</guid>
            <dc:creator><![CDATA[Sam Wang]]></dc:creator>
            <pubDate>Wed, 19 Nov 2014 09:37:05 GMT</pubDate>
            <atom:updated>2014-11-19T11:17:41.528Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift is an awesome language, it’s safe, it’s simple and easy learning, but sometimes we still need to use the existed project which written in Objective-C previously, how should we do at this moment?</p><p>That’s take the project I created for mosquitto client as an example. (<a href="https://github.com/samwang0723/libmosquitto">https://github.com/samwang0723/libmosquitto</a>)</p><h4>Mosquitto &amp; MQTT</h4><blockquote><em>“MQTT is a machine-to-machine (M2M)/”Internet of Things” connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. It is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium.”</em></blockquote><p>MQTT is a milestone of <strong>The Internet of Things (IoT)</strong>, with MQTT, you can create an instant message App, communicate with terminal devices, Home automation, etc… MQTT’s <strong>subscribe/publish</strong> mechanism which saves the network traffic and power, not like traditional Socket (persistent connection), MQTT using <strong>ping</strong> to detect the client and transmit message when existed.</p><p><a href="http://mosquitto.org/">Mosquitto</a> is an open source (<a href="http://mosquitto.org/COPYING.txt">BSD licensed</a>) message broker that implements the <a href="http://mqtt.org/">MQ Telemetry Transport</a> protocol versions 3.1 and 3.1.1., with Mosquitto, developers can easily establish the environment on their computers/servers.</p><h4>Install Mosquitto</h4><p>There are many ways to install mosquitto on your computer, in this article I use MacOS, so I will install it through <strong>“brew install mosquitto”</strong>, you can follow the <strong>Binary Installation</strong> instruction here: <a href="http://mosquitto.org/download/">http://mosquitto.org/download/</a></p><p>After installation complete, you will see there is an executable “mosquitto” on <strong>/usr/local/Cellar/mosquitto/(version)/sbin</strong>, execute it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*RSNz1NI-nNp6eVWoVHcrBg.png" /></figure><p>mosquitto will use default configuration and bind with port 1883 as a MQTT broker.</p><h4>Build libmosquitto</h4><p>Download the project from my <a href="https://github.com/samwang0723/libmosquitto">github</a> and build, you will have three headers and one static library(universal build already has all architectures of iOS CPU), these contains the main function of mosquitto client, we have to import it into our Swift project.</p><h4>Bridging Header</h4><p>In WWDC 2014 tutorial video session, we understand that Swift code can be embed into Objective-c project, and Objective-c can also include with Swift project. <a href="https://developer.apple.com/videos/wwdc/2014/?id=402">https://developer.apple.com/videos/wwdc/2014/?id=402</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*216V82EGkqr3gFL_D9RcSg.png" /></figure><p>Reference from above picture, we realized the bridge header is needed, there are three headers for libmosquitto right now, <strong>MosquittoClient.h, MosquittoMessage.h and mosquitto.h</strong>, and I am going to bridge them into <strong>Mosquitto-Bridging-Header.h </strong>(File-&gt;New-&gt;File-&gt;Header file)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*twHPqLV4XCs_I2YbnudFeA.png" /></figure><p>Next we are going to make sure the <strong>Build Phases</strong> contains above headers in our Swift project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*F16VerKpNCWaLC5jRC9mIw.png" /></figure><p>In <strong>Build Settings</strong>, add bridging header file location into <strong>Swift Compiler</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*OiX6sxoZqfvDjqscEquFhA.png" /></figure><h4>Code Implementation</h4><p>After all settings are done, let’s create a instance of MosquittoClient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*h0bQbPBE4UqqKOQEhG9s4A.png" /></figure><p>See! this sample use MosquittoClient without import anything. Bridging header helps to transform Objective-c into Swift format, even if the delegate.</p><p>If we implemented the <strong>MosquittoClientDelegate</strong>, press <strong>“esc”</strong> to list the candidate of functions and you can see all delegate methods in Swift format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*CmIzHLc6N1ngo2p4uyE4Sw.png" /></figure><p>Alright, now is the time to complete the code, create MosquittoClient with certain ID, set connection target to <strong>127.0.0.1</strong> on port <strong>1883 </strong>(these parameters depends on your MQTT broker environment), then connect().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*u0vlxgnWbQYoOBNoKKYQ5Q.png" /></figure><p>Then, in didConnect callback, we subscribe certain topic(<strong>“sample”</strong>) if connect success.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*PSRkzz3yJpd8bXikQZR0YQ.png" /></figure><p>After launch on simulator or actual iPhone/iPad, you can see the connection established information from terminal or Xcode debug console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*oE1hPQwM1E5iq9JcIVcZWA.png" /></figure><p>Next we use <strong>mosquito_pub</strong> to publish message with certain topic.</p><pre><em>./mosquitto_pub -t “sample” -m “hello swift” -q 1</em></pre><p>App can received message from callback</p><pre><em>didReceiveMessage, msg=hello swift</em></pre><h4>Conclusion</h4><p>This tutorial shows how to reuse the Objective-c code/library with Swift project, Apple doesn’t want developer to abandon the Objective-c project at all, and you don’t have to rewrite all things, just use <strong>bridge header </strong>to achieve your goal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87ce0b6ec513" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-programming/merge-objective-c-static-library-into-swift-using-mosquitto-87ce0b6ec513">Merge Objective-C static library into Swift (using mosquitto)</a> was originally published in <a href="https://medium.com/swift-programming">Swift Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn NSURLSession using Swift Part 3— Upload]]></title>
            <link>https://medium.com/swift-programming/learn-nsurlsession-using-swift-part-3-upload-3a5be9a69950?source=rss-b8f85c66ee49------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a5be9a69950</guid>
            <dc:creator><![CDATA[Sam Wang]]></dc:creator>
            <pubDate>Fri, 07 Nov 2014 04:17:59 GMT</pubDate>
            <atom:updated>2014-11-07T04:17:59.555Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn NSURLSession using Swift Part 3— Upload</p><p>In <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html#//apple_ref/doc/uid/TP40013509-SW23">URL Loading System Programming Guide</a>, Apple mentioned there are four ways to upload content.</p><ol><li>Uploading Body Content Using an NSData Object</li><li>Uploading Body Content Using a File</li><li>Uploading Body Content Using a Stream</li><li>Uploading a File Using a Download Task</li></ol><p>The first and second one are the most useful items for me, basically you don’t have to set those complicated header values on your own, only focus on upload body content. The session object <strong>computes the Content-Length header based on the size of the data object</strong> if you using NSData or File type, and if your app does not provide a value for theContent-Type header, the <strong>session also provides one</strong>.</p><p>(P.S. I think the screen capture image is better for viewing rather than type code on Medium, if you need copy the sample code, please download full project: <a href="https://github.com/samwang0723/URLSessionUpload">https://github.com/samwang0723/URLSessionUpload</a> )</p><h4>Upload using NSData</h4><p>Now let us to test the upload function using Python SimpleHTTPServer, if you are not familiar with Python, just use the code below(<strong>execute in console ./SimpleHTTPServerWithUpload.py</strong>) and save the retrieved file to Desktop on your Mac (In this example I will write swift.png, you can modify the file name you want). This server allows you to POST a file and will return “Upload Complete” while upload complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*UtC5b03Hiv88opYSNwBO7Q.png" /></figure><p>Next I create a project to store the image file to Bundle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*VZc0PFPOaIGKKxhbCh2CmA.png" /></figure><p>Then I read the file in Bundle and save as NSData object.</p><pre><em>let bundle = NSBundle.mainBundle()<br>let path = bundle.pathForResource(“swift”, ofType: “png”)<br>var data: NSData = NSData(contentsOfFile: path!)</em></pre><p>And create a NSMutableURLRequest for handling the upload request, <strong>set HTTP method to “POST”.</strong></p><pre><em>var request = NSMutableURLRequest(URL: NSURL(string: “http://127.0.0.1:8000/swift.png&quot;))<br>request.HTTPMethod = “POST”<br>request.setValue(“Keep-Alive”, forHTTPHeaderField: “Connection”)</em></pre><p>Next, like previous article described, we need to create the NSURLSession, this time using a <strong>defaultSessionConfiguration </strong>and<strong> </strong>implement delegate on ViewController itself, whole code will be like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*-EmZSs3Qu14wV6Mhp9UC5w.png" /></figure><h4>Handling Response with Delegate</h4><p>Noticed that I implemented four delegate methods, we can realize the upload progress using <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionTaskDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionTaskDelegate/URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:">URLSession:task:didSendBodyData:totalBytesSent:<br>totalBytesExpectedToSend:</a> , compute progress float by</p><pre><em>var uploadProgress: Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)</em></pre><p>And receive response from <strong>didReceiveData, didReceiveResponse</strong>, append the result using NSMutableData, then I will handle the completion with <strong>didCompleteWithError</strong>, the reason this method will be triggered is because I <strong>didn’t use the completion Closure in uploadTaskWithRequest</strong>, or you can handle the completion in Closure if you want to, convert the NSMutableData into String result.</p><h4>Execute</h4><p>You can see the server console log will print the incoming POST request detail:</p><pre><em>web server on 8000..<br>Host: 127.0.0.1:8000<br>Content-Type: application/x-www-form-urlencoded<br>User-Agent: NSURLSessionUpload/1 CFNetwork/711.0.6 Darwin/14.0.0<br>Accept: */*<br>Accept-Language: en-us<br>Content-Length: 2849623<br>Accept-Encoding: gzip, deflate<br>Connection: keep-alive</em></pre><pre><em>2849623<br>127.0.0.1 — — [07/Nov/2014 11:17:27] “POST /swift.png HTTP/1.1&quot; 200 -</em></pre><p>Logs in Xcode:</p><pre><em>session &lt;__NSURLSessionLocal: 0x7fe559517560&gt; uploaded 93.1424255371094%.<br>session &lt;__NSURLSessionLocal: 0x7fe559517560&gt; uploaded 94.2923278808594%.<br>session &lt;__NSURLSessionLocal: 0x7fe559517560&gt; uploaded 95.4422378540039%.<br>session &lt;__NSURLSessionLocal: 0x7fe559517560&gt; uploaded 96.5921478271484%.<br>session &lt;__NSURLSessionLocal: 0x7fe559517560&gt; uploaded 97.7420501708984%.<br>session &lt;__NSURLSessionLocal: 0x7fe559517560&gt; uploaded 98.891960144043%.<br>session &lt;__NSURLSessionLocal: 0x7fe559517560&gt; uploaded 100.0%.<br>session &lt;__NSURLSessionLocal: 0x7fe559517560&gt;, received response &lt;NSHTTPURLResponse: 0x7fe5595208a0&gt; { URL: </em><a href="http://127.0.0.1:8000/swift.png"><em>http://127.0.0.1:8000/swift.png</em></a><em> } { status code: 200, headers {<br> “Content-Type” = “text/html;charset=utf-8&quot;;<br> Date = “Fri, 07 Nov 2014 03:17:27 GMT”;<br> Server = “BaseHTTP/0.3 Python/2.7.6&quot;;<br>} }<br>session &lt;__NSURLSessionLocal: 0x7fe559517560&gt; upload completed, response: Upload Complete</em></pre><h4>Content Type</h4><p>If we use the upload task without provide the Content-Type header field, NSURLSession will gives us the <strong>“application/x-www-form-urlencoded”</strong>, which is an<strong> </strong>“old” format (as the query string or as a single data part of type <em>application/x-www-form-urlencoded). </em>Most of the servers support the well-known new MIME media type, “multipart/form-data” now, so I will suggest you to define the Content-Type before send out the request.</p><h4>Background Upload</h4><p>Upload task also support background execution, you can simply change the configuration to <strong>backgroundSessionConfiguration, </strong>if you have problems to setup the configuration, please refer to part 2: <a href="https://medium.com/swift-programming/learn-nsurlsession-using-swift-part-2-background-download-863426842e21">https://medium.com/swift-programming/learn-nsurlsession-using-swift-part-2-background-download-863426842e21</a></p><h4>Handle Stream Upload</h4><p>If you have large file, better to use streaming upload with chunked header, the NSMutableURLRequest should be modify with these additional items:</p><pre><em>request.setValue(“application/octet-stream”, forHTTPHeaderField: “Content-Type”)<br>request.HTTPBodyStream = NSInputStream(data: data)</em></pre><p>And because the session cannot necessarily rewind the provided stream to re-read data, your app is responsible for providing a new stream in the event that the session must retry a request (for example, if authentication fails). To do this, your app provides a<a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionTaskDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionTaskDelegate/URLSession:task:needNewBodyStream:">URLSession:task:needNewBodyStream:</a> method. When that method is called, your app should perform whatever actions are needed to obtain or create a new body stream, and then call the provided completion handler block with the new stream.</p><p>(Note: The Python server sample here doesn’t support streaming data transfer)</p><h4>Conclusion</h4><p>So far we learned how to download and upload no matter in foreground or background, I believe these are enough for a developer to handle the HTTP network communication. Another topic I didn’t discuss about is <strong>Ephemeral sessions</strong>, it depends on the usage of your App and will not cache any content to local disk, think about the private browsing in Safari, if you need the similar usage in your App, use with <strong>Ephemeral sessions.</strong></p><p>Thanks again for viewing my articles, and please feel free to contact with me if any questions or suggestion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a5be9a69950" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-programming/learn-nsurlsession-using-swift-part-3-upload-3a5be9a69950">Learn NSURLSession using Swift Part 3— Upload</a> was originally published in <a href="https://medium.com/swift-programming">Swift Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn NSURLSession using Swift Part 2 — Background download]]></title>
            <link>https://medium.com/swift-programming/learn-nsurlsession-using-swift-part-2-background-download-863426842e21?source=rss-b8f85c66ee49------2</link>
            <guid isPermaLink="false">https://medium.com/p/863426842e21</guid>
            <dc:creator><![CDATA[Sam Wang]]></dc:creator>
            <pubDate>Tue, 04 Nov 2014 09:09:35 GMT</pubDate>
            <atom:updated>2014-11-05T06:18:49.177Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn NSURLSession using Swift Part 2 — Background download</p><p>Based on previous article (<a href="https://medium.com/@0723Sam/learn-nsurlsession-using-swift-ebd80205f87c">Learn NSURLSession using Swift Part 1 — HTTP/HTTPS GET</a>), we already understand what NSURLSession can do for us. Now, let’s find out the most important behavior — <strong>Background Downloads</strong>.</p><h4>Reason</h4><p>Users apparently loves to download some useful stuff on their cell-phone, like images, music, etc. Using Apps which provides download behavior is joyful, but it’s better if we can left the App to finish its job in background and use other Apps in foreground at same time, then back to see the download results after a while.</p><h4>Source Code</h4><p>Since we are going to present download process based on the App lifecycle, this time I will demo using entire Swift project, you can download the source code here: <a href="https://github.com/samwang0723/URLSessionBackgroundDownload">https://github.com/samwang0723/URLSessionBackgroundDownload</a></p><h4>Session Identifier and create Session &amp; Task</h4><p>As previously mentioned, there are three kinds of types of NSURLSession, we are going to use <strong>download sessions</strong> with <strong>background configuration</strong> to enable background download in this tutorial. Refer to (<a href="https://developer.apple.com/library/IOs/documentation/Foundation/Reference/NSURLSessionConfiguration_class/index.html#//apple_ref/occ/clm/NSURLSessionConfiguration/backgroundSessionConfigurationWithIdentifier:">backgroundSessionConfigurationWithIdentifier(_</a>: ), The unique identifier for the configuration object. This parameter must not be nil or an empty string. In below code sample I created a struct to store our identifier as <strong>static</strong>, because it will be use in many place.</p><pre><em>struct SessionProperties {<br>     static let identifier:String! = <br>                     “url_session_background_download”<br>}</em></pre><p>Then I’m gonna create the background configuration</p><pre><em>var configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(SessionProperties.identifier)</em></pre><p>And create background session</p><pre><em>var backgroundSession = NSURLSession(configuration: configuration, delegate: self.delegate, delegateQueue: nil)</em></pre><h4>Custom Delegate</h4><p>Notice that we need to have a customized delegate(self.delegate), implement <strong>NSURLSessionDelegate</strong>, <strong>NSURLSessionDownloadDelegate</strong>, I made this delegate with <strong>singleton(</strong>called with sharedInstance<strong>)</strong> and can allow access by different activity without duplicate many copies.</p><pre><em>typealias CompleteHandlerBlock = () -&gt; ()</em></pre><pre><em>class DownloadSessionDelegate : NSObject, NSURLSessionDelegate, NSURLSessionDownloadDelegate {<br> <br>   var handlerQueue: [String : CompleteHandlerBlock]!<br>   class var sharedInstance: DownloadSessionDelegate {<br>       struct Static {<br>            static var instance : DownloadSessionDelegate?<br>            static var token : dispatch_once_t = 0<br>       }<br> <br>       dispatch_once(&amp;Static.token) {<br>            Static.instance = DownloadSessionDelegate()<br>            Static.instance!.handlerQueue = [String : <br>                                         CompleteHandlerBlock]()<br>       }<br> <br>       return Static.instance!<br>   }<br> <br>   //MARK: session delegate<br>   func URLSession(session: NSURLSession, didBecomeInvalidWithError <br>                                                 error: NSError?) {<br>       println(“session error: \(error?.localizedDescription).”)<br>   }<br> <br>   func URLSession(session: NSURLSession, didReceiveChallenge <br>                   challenge: NSURLAuthenticationChallenge, <br>                   completionHandler: <br>                         (NSURLSessionAuthChallengeDisposition, <br>                                       NSURLCredential!) -&gt; Void) {<br>       completionHandler(<br>              NSURLSessionAuthChallengeDisposition.UseCredential, <br>              NSURLCredential(forTrust: <br>                            challenge.protectionSpace.serverTrust))<br>   }<br> <br>   func URLSession(session: NSURLSession, <br>                   downloadTask:NSURLSessionDownloadTask, <br>                   didFinishDownloadingToURL location: NSURL) {<br>        println(“session \(session) has <br>                 finished the download task \(downloadTask) of URL <br>                 \(location).”)<br>   }<br> <br>   func URLSession(session: NSURLSession, <br>                   downloadTask: NSURLSessionDownloadTask, <br>                   didWriteData bytesWritten: Int64, <br>                   totalBytesWritten: Int64, <br>                   totalBytesExpectedToWrite: Int64) {<br>        println(“session \(session) download task \(downloadTask) <br>                wrote an additional \(bytesWritten) bytes (total \<br>               (totalBytesWritten) bytes) out of an expected \<br>               (totalBytesExpectedToWrite) bytes.”)<br>   }</em></pre><pre><em>   func URLSessionDidFinishEventsForBackgroundURLSession(session: <br>                                                  NSURLSession) {<br>         println(“background session \(session) finished events.”)<br> <br>         if !session.configuration.identifier.isEmpty {<br>              callCompletionHandlerForSession(<br>                            session.configuration.identifier)<br>         }<br>   }<br> <br>   //MARK: completion handler<br>   func addCompletionHandler(handler: CompleteHandlerBlock, <br>                                            identifier: String) {<br>         handlerQueue[identifier] = handler<br>   }<br> <br>   func callCompletionHandlerForSession(identifier: String!) {<br>         var handler : CompleteHandlerBlock = <br>                                    handlerQueue[identifier]!<br>         handlerQueue!.removeValueForKey(identifier)<br>         handler()<br>   }<br>}</em></pre><p>In <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionDownloadDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionDownloadDelegate/URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:">URLSession(_:downloadTask:didWriteData:totalBytesWritten:<br>totalBytesExpectedToWrite</a>, we can receive the callback from current download process and tell the written bytes, this delegate method can use to calculate the download progress percentage by <strong>“var progress = totalBytesWritten / totalBytesExpectedToWrite”</strong>.</p><p>In <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionDownloadDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionDownloadDelegate/URLSession:downloadTask:didFinishDownloadingToURL:">URLSession(_:downloadTask:didFinishDownloadingToURL</a> means the download has finished. <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionDelegate/URLSessionDidFinishEventsForBackgroundURLSession:">URLSessionDidFinishEventsForBackground<br>URLSession(_</a>: ) Tells the delegate that all messages enqueued for a background session have been delivered.</p><h4>AppDelegate will handle the resume while download completed</h4><p>The last two functions <strong>addCompletionHandler, callCompletionHandlerForSession </strong>used for handle complete notification from AppDelegate, when user put your App into background, the download will still proceed and automatically relaunched your App when a download completes by calling <a href="https://developer.apple.com/library/IOs/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/index.html#//apple_ref/occ/intfm/UIApplicationDelegate/application:handleEventsForBackgroundURLSession:completionHandler:">application:handleEventsForBackgroundURLSession:<br>completionHandler:</a> in AppDelegate as below.</p><pre><em>//MARK: background session handling<br>func application(application: UIApplication, <br>           handleEventsForBackgroundURLSession identifier: String, <br>                                  completionHandler: () -&gt; Void) {<br>    println(“— handleEventsForBackgroundURLSession —”)<br>    var backgroundConfiguration = NSURLSessionConfiguration.<br>      backgroundSessionConfigurationWithIdentifier(identifier)<br>    var backgroundSession = NSURLSession(configuration: <br>             backgroundConfiguration, delegate: self.delegate, <br>             delegateQueue: nil)<br>    println(“Rejoining session \(backgroundSession)”)<br> <br>    self.delegate.addCompletionHandler(completionHandler, <br>                                         identifier: identifier)<br>}</em></pre><p>When background download complete and trigger AppDelegate, we retrieve back the session use identifier, and put the completionHandler into queue, while our custom delegate receive the <strong>URLSessionDidFinishEventsFor<br>BackgroundURLSession</strong>, we can get the Closure and execute it to complete the whole process, it is really important because calling completion handler lets the system know that your app’s user interface is updated and a new snapshot can be taken.</p><p>Now implement the download task, you can simply create a download task with <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/#//apple_ref/occ/instm/NSURLSession/downloadTaskWithRequest:">downloadTaskWithRequest(_</a>: ), and perform it with <strong>resume()</strong></p><pre><em>var url = NSURLRequest(URL: NSURL(string: data[4])!)<br>var downloadTask = backgroundSession.downloadTaskWithRequest(url)<br>downloadTask.resume()</em></pre><h4>Project Setup for Background Mode</h4><p>Most of the documents said the code above should be able to let developers to enable background download, but actually I can’t, the reason is that I didn’t enable <strong>Background Modes</strong> in the <strong>Project Capabilities.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*vpIfsJ8oDtPkI_m-dy16bg.png" /></figure><p>Right now execute these code on your iPhone, and you can see what’s happen if put App to background while downloading(press Home key), and waiting to be triggered when download complete.</p><pre><em>session &lt;__NSURLBackgroundSession: 0x170128480&gt; download task &lt;__NSCFBackgroundDownloadTask: 0x125d140a0&gt;{ taskIdentifier: 1 } wrote an additional 65536 bytes (total 234795690 bytes) out of an expected 262144000 bytes.</em></pre><pre><em>session &lt;__NSURLBackgroundSession: 0x170128480&gt; download task &lt;__NSCFBackgroundDownloadTask: 0x125d140a0&gt;{ taskIdentifier: 1 } wrote an additional 65536 bytes (total 234867558 bytes) out of an expected 262144000 bytes.</em></pre><pre><em>session &lt;__NSURLBackgroundSession: 0x170128480&gt; download task &lt;__NSCFBackgroundDownloadTask: 0x125d140a0&gt;{ taskIdentifier: 1 } wrote an additional 65536 bytes (total 234938070 bytes) out of an expected 262144000 bytes.</em></pre><pre><em>session &lt;__NSURLBackgroundSession: 0x170128480&gt; download task &lt;__NSCFBackgroundDownloadTask: 0x125d140a0&gt;{ taskIdentifier: 1 } wrote an additional 65536 bytes (total 235015362 bytes) out of an expected 262144000 bytes.</em></pre><pre><em>— handleEventsForBackgroundURLSession —</em></pre><pre><em>2014–11–04 16:51:13.070 URLSessionBackgroundDownload[13461:2121612] A background URLSession with identifier url_session_background_download already exists!</em></pre><pre><em>Rejoining session &lt;__NSURLBackgroundSession: 0x170128480&gt;</em></pre><pre><em>session &lt;__NSURLBackgroundSession: 0x170128480&gt; has finished the download task &lt;__NSCFBackgroundDownloadTask: 0x125d140a0&gt;{ taskIdentifier: 1 } of URL file:///private/var/mobile/Containers/Data/Application/23F2A8ED-14BC-485E-B747-C651B000CDA7/Library/Caches/com.apple.nsurlsessiond/Downloads/org.samwang.URLSessionBackgroundDownload/CFNetworkDownload_7KoBTL.tmp.</em></pre><pre><em>background session &lt;__NSURLBackgroundSession: 0x170128480&gt; finished events.</em></pre><p>And of course, please move the temporary file into Document or some place in <strong>didFinishDownloadingToURL</strong> delegate method.</p><p>Next chapter we can discuss about the upload related topic of NSURLSession, hope you will like it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=863426842e21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-programming/learn-nsurlsession-using-swift-part-2-background-download-863426842e21">Learn NSURLSession using Swift Part 2 — Background download</a> was originally published in <a href="https://medium.com/swift-programming">Swift Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn NSURLSession using Swift Part 1 — HTTP/HTTPS GET]]></title>
            <link>https://medium.com/swift-programming/learn-nsurlsession-using-swift-ebd80205f87c?source=rss-b8f85c66ee49------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebd80205f87c</guid>
            <dc:creator><![CDATA[Sam Wang]]></dc:creator>
            <pubDate>Mon, 03 Nov 2014 07:00:17 GMT</pubDate>
            <atom:updated>2014-12-09T03:46:49.053Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn NSURLSession using Swift Part 1 - HTTP/HTTPS GET</p><blockquote><em>“In iOS7 and later or OS X v10.9 and later, NSURLSession is the preferred API for new code that performs URL requests” — Apple</em></blockquote><p>Usually, when an iOS developers wants to retrieve contents from certain URL, they choose to use NSURLConnection. In iOS 7 and later, Apple suggest to use NSURLSession instead, NSURLSession is just like an improvement or you can consider as a refactoring, I would like to say it is a “Mutation”.</p><p><strong>There are three types of NSURLSession:</strong></p><p>a) default sessions: behaviour like NSURLConnection<br>b) ephemeral sessions: not cache any content to disk<br>c) download sessions: store the result in file and transferring data even when app is suspended, exits or crashes</p><p><strong>Based on above sessions, developers can schedule three types of tasks:</strong></p><p>a) data tasks: retrieve data to memory<br>b) download tasks: download file to disk<br>c) upload tasks: uploading file from disk and receiving response as data in memory</p><p>We can implement a simple HTTP request using Swift Playground:</p><pre><em>import Foundation<br>import XCPlayground</em></pre><pre><em>func httpGet(request: NSURLRequest!, callback: (String, String?) -&gt; Void) {<br>    var session = NSURLSession.sharedSession()<br>    var task = session.dataTaskWithRequest(request){<br>         (data, response, error) -&gt; Void in<br>         if error != nil {<br>             callback(“”, error.localizedDescription)<br>         } else {<br>             var result = NSString(data: data, encoding:<br>                                   NSASCIIStringEncoding)!<br>             callback(result, nil)<br>         }<br>    }<br>    task.resume()<br>}</em></pre><pre><em>var request = NSMutableURLRequest(URL: NSURL(string: “</em><a href="http://www.google.com/"><em>http://www.google.com</em></a><em>&quot;)!)<br>httpGet(request){<br>   (data, error) -&gt; Void in<br>   if error != nil {<br>       println(error)<br>   } else {<br>       println(data)<br>   }<br>}</em></pre><pre><em>XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)</em></pre><p>In above code section, we use a default session with data task to retrieve Google contents. <a href="https://developer.apple.com/library/IOs/documentation/Foundation/Reference/NSURLSession_class/index.html#//apple_ref/occ/clm/NSURLSession/sharedSession"><strong>NSURLSession.sharedSession()</strong></a> returns a singleton session based on default configuration. Then, use this session to create a data task(<a href="https://developer.apple.com/library/IOs/documentation/Foundation/Reference/NSURLSession_class/index.html#//apple_ref/occ/instm/NSURLSession/dataTaskWithURL:completionHandler:"><strong>session.dataTaskWithRequest</strong></a>), bring the URLRequest in and handle the Closures. Finally, execute this task by calling <a href="https://developer.apple.com/library/IOs/documentation/Foundation/Reference/NSURLSessionTask_class/index.html#//apple_ref/occ/instm/NSURLSessionTask/resume"><strong>task.resume()</strong></a><strong>.</strong></p><p>Really simple, isn’t it? What if we wants to retrieve the HTTPS protocol contents?</p><p>Let’s try to modify URL in previous code section to <strong>“https://www.google.com”</strong>.</p><p>You will see the results in console like below:</p><pre><em>NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807)</em></pre><p>The flow of authentication will choose the handle delegate, if you didn’t implement the session level delegate<br>(<a href="https://developer.apple.com/library/IOs/documentation/Foundation/Reference/NSURLSessionDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionDelegate/URLSession:didReceiveChallenge:completionHandler:">URLSession:didReceiveChallenge:completionHandler:</a>), it will pass to task level delegate(<a href="https://developer.apple.com/library/IOs/documentation/Foundation/Reference/NSURLSessionTaskDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionTaskDelegate/URLSession:task:didReceiveChallenge:completionHandler:">URLSession:task:didReceiveChallenge:completionHandler:</a>).</p><p>That means we need to have delegate implementation since the default system delegate didn’t help us to handle these behavior.</p><pre><em>class LearnNSURLSession: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate {<br>   typealias CallbackBlock = (result: String, error: String?) -&gt; ()<br>   var callback: CallbackBlock = {<br>       (resultString, error) -&gt; Void in<br>       if error == nil {<br>           println(resultString)<br>       } else {<br>           println(error)<br>       }<br>   }<br> <br>   func httpGet(request: NSMutableURLRequest!, callback: (String, <br>                                             String?) -&gt; Void) {<br>        var configuration = <br>           NSURLSessionConfiguration.defaultSessionConfiguration()<br>        var session = NSURLSession(configuration: configuration, <br>                      delegate: self, <br>                      delegateQueue:NSOperationQueue.mainQueue())<br>        var task = session.dataTaskWithRequest(request){<br> (data: NSData!, response: NSURLResponse!, error: NSError!) -&gt; Void in<br>            if error != nil {<br>               callback(“”, error.localizedDescription)<br>            } else {<br>               var result = NSString(data: data, encoding:  <br>                                       NSASCIIStringEncoding)!<br>               callback(result, nil)<br>            }<br>        }<br>        task.resume()<br>   }</em></pre><pre><em>   func URLSession(session: NSURLSession, <br>                 didReceiveChallenge challenge: <br>                              NSURLAuthenticationChallenge, <br>                 completionHandler: <br>                             (NSURLSessionAuthChallengeDisposition, <br>                             NSURLCredential!) -&gt; Void) {<br>          completionHandler(<br>            NSURLSessionAuthChallengeDisposition.UseCredential, <br>            NSURLCredential(forTrust: <br>                       challenge.protectionSpace.serverTrust))<br>   }<br><br>   func URLSession(session: NSURLSession, <br>                 task: NSURLSessionTask, <br>                 willPerformHTTPRedirection response:       <br>                                      NSHTTPURLResponse, <br>                 newRequest request: NSURLRequest, <br>                 completionHandler: (NSURLRequest!) -&gt; Void) {<br>          var newRequest : NSURLRequest? = request<br>          println(newRequest?.description);<br>          completionHandler(newRequest)<br>    }<br>}</em></pre><pre><em>var learn = LearnNSURLSession()<br>var request = NSMutableURLRequest(URL: NSURL(string: “</em><a href="https://www.google.com/"><em>https://www.google.com</em></a><em>&quot;)!)<br>learn.httpGet(request) {<br>     (resultString, error) -&gt; Void in<br>     learn.callback(result: resultString, error: error)<br>}</em></pre><p>Inside LearnNSURLSession class we inherit the NSObject and implement <strong>NSURLSessionDelegate, NSURLSessionTaskDelegate</strong> to handle HTTPS authentication and redirection. While executing <strong>httpGet </strong>with “https://www.google.com”, it will first redirect by server to the final destination, we can handle the redirect manually or just bypass it(in this case we bypass it and handle nothing) through delegate method in <strong>NSURLSessionTaskDelegate</strong>(<a href="https://developer.apple.com/library/IOs/documentation/Foundation/Reference/NSURLSessionTaskDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionTaskDelegate/URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:">URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler</a>:).</p><p>Next, we should implement the <strong>didReceiveChallenge</strong> for listening challenge request from server. There are many ways to response challenge to server, some may use the username/password or other way to create credential, we just use <strong>serverTrust</strong> here and pass the <strong>NSURLCredential</strong> into completion. (<a href="https://developer.apple.com/library/IOs/documentation/Foundation/Reference/NSURLSessionDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionDelegate/URLSession:didReceiveChallenge:completionHandler:">URLSession(_:didReceiveChallenge:completionHandler</a>:)</p><pre><em>completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust:challenge.protectionSpace.serverTrust))</em></pre><p>Now execute it and you can see the results.</p><p>In next chapter, I will introduce you the background download while App not in foreground.</p><p>References:<br><a href="https://developer.apple.com/library/IOs/documentation/Foundation/Reference/NSURLSession_class/index.html#">https://developer.apple.com/library/IOs/documentation/Foundation/Reference/NSURLSession_class/index.html</a></p><p><a href="https://developer.apple.com/library/IOs/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html#//apple_ref/doc/uid/TP40013509-SW1">https://developer.apple.com/library/IOs/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html#//apple_ref/doc/uid/TP40013509-SW1</a></p><p><a href="https://developer.apple.com/library/IOs/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/AuthenticationChallenges.html#//apple_ref/doc/uid/TP40009507-SW1">https://developer.apple.com/library/IOs/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/AuthenticationChallenges.html#//apple_ref/doc/uid/TP40009507-SW1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd80205f87c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-programming/learn-nsurlsession-using-swift-ebd80205f87c">Learn NSURLSession using Swift Part 1 — HTTP/HTTPS GET</a> was originally published in <a href="https://medium.com/swift-programming">Swift Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>