<?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 Nutchaphon Rewik on Medium]]></title>
        <description><![CDATA[Stories by Nutchaphon Rewik on Medium]]></description>
        <link>https://medium.com/@nrewik?source=rss-b75c758c5100------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ypx1X8Q0b22QyzQwB2cwag.jpeg</url>
            <title>Stories by Nutchaphon Rewik on Medium</title>
            <link>https://medium.com/@nrewik?source=rss-b75c758c5100------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:13:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nrewik/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[แอพฉลาดชาติเจริญ—ใช้ Deep Learning บน iOS ด้วย Caffe 2]]></title>
            <link>https://medium.com/@nrewik/%E0%B9%81%E0%B8%AD%E0%B8%9E%E0%B8%89%E0%B8%A5%E0%B8%B2%E0%B8%94%E0%B8%8A%E0%B8%B2%E0%B8%95%E0%B8%B4%E0%B9%80%E0%B8%88%E0%B8%A3%E0%B8%B4%E0%B8%8D-%E0%B9%83%E0%B8%8A%E0%B9%89-deep-learning-%E0%B8%9A%E0%B8%99-ios-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-caffe-2-22e26dde1fb4?source=rss-b75c758c5100------2</link>
            <guid isPermaLink="false">https://medium.com/p/22e26dde1fb4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[caffe]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Nutchaphon Rewik]]></dc:creator>
            <pubDate>Sat, 13 May 2017 06:32:47 GMT</pubDate>
            <atom:updated>2017-05-13T07:16:13.820Z</atom:updated>
            <content:encoded><![CDATA[<p>จากกระแสของ AI ที่ใครๆ ก็พูดถึงแต่ Deep Learning และแต่ละวันที่ผมเห็นข่าวของ Deep Learning ว่ามันทำนู่นได้ ทำนี่ได้ จึงเกิดอาการ Hype ประมาณว่า “เฮ้ยทำไมมันเจ๋งจังวะ”, “แม่งโคตรโกง”, “อาชีพ…เตรียมตัวตกงานได้เลย”</p><p>เอาล่ะ Hype ไปก็เท่านั้น จะรออะไรล่ะ ลองเล่นมันเลยละกัน !! เอามันมาใช้กับแอพเรา !!</p><h3>Caffe 2</h3><p>Caffe 2 คือ Deep Learning Framework จาก Facebook ที่ถูกออกแบบและปรับแต่งมาโดยเฉพาะให้เข้ากับการใช้งานบนมือถือ ข้อดีของ Caffe 2 ที่ทาง Facebook เค้าเคลมไว้คือ เบา(lightweight) และเร็ว แถมยังเป็น cross platform อีกต่างหาก</p><p>บทความนี้จะสอนเกี่ยวกับการใช้งาน Caffe 2 บน iOS โดยจะเป็นตัวอย่างของการใช้ Deep Learning Model ที่ถูกฝัง (embed) ลงบนมือถือ โดยเราจะมาเขียนแอพกัน ในแอพนี้ เราจะสามารถเลือกรูปอะไรก็ได้มาซักรูป แล้วแอพของเราก็จะทำนายว่า รูปที่เลือกมาน่ะ คือรูปอะไร</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M0GTwH0ynwSlZfYj5r4jhg.png" /></figure><p>บทความนี้จะแบ่งเป็น 3 เรื่องใหญ่ๆ คือ</p><ol><li>ความรู้ขั้นเบสิคของการใช้งาน Deep Learning Framework</li><li>การติดตั้ง Caffe 2 และการนำมาใช้ใน Xcode</li><li>ลงมือเขียนโค้ด</li></ol><p>ท่านสามารถดาวน์โหลดโปรเจค Xcode ที่เสร็จแล้ว ไปลองเล่นกันได้ที่นี่ <a href="https://github.com/nRewik/caffe2-ios-sample">github.com/nrewik/caffe2-ios-sample</a></p><h3>การใช้งาน Deep Learning Framework</h3><p>ผมขอแบ่งเป็นสองส่วนให้เข้าใจง่ายๆ คือ</p><ol><li>สร้าง Model</li><li>นำ Model มาใช้</li></ol><h3>Model คืออะไร</h3><p>Model ที่ว่าเนี่ย ไม่ใช่ Model class ใน MVC อะไรแบบนั้นนะ ใน Machine Learning เนี่ย Model ที่ว่าคือ เครื่องมือที่ใช้ทำนาย โดยภายใน Model ก็จะมีการ เก็บโครงสร้าง เก็บค่าตัวแปรต่างๆ ซึ่งเมื่อเราใส่ input เข้าไป มันก็จะทำงาน และคำนวณผลลัพธ์ออกมาให้เรา ซึ่งผลลัพธ์ที่ว่าก็คือ คำทำนาย นั่นเอง</p><h3>การสร้าง Model</h3><p>การจะสร้าง Modelๆ นึง จริงๆมันมีอยู่หลายขั้นตอนมาก ผมขอสรุป workflow คร่าวๆ เป็นแบบนี้ละกัน</p><ol><li>ออกแบบและปรับแต่งโครงสร้างของ Model ไม่ว่าจะเป็น เลือกวิธี, เลือก algorithm, ตั้งค่าตัวแปร, เลือก layer, บลาๆๆ</li><li>นำข้อมูลมาฝึก ให้ Model มันเรียนรู้ และฉลาดขึ้น</li><li>เมื่อฝึกไปได้ถึงจุดๆนึง เราจะเอา Model มาวัดผลความแม่นยำของการทำนาย</li></ol><p>โดยเราจะทำวนๆ ข้อ 1–3 ไปเรื่อยๆ จนกว่าเราจะพอใจกับผลลัพธ์ จนสุดท้ายเราจะนำ Model ที่เราคิดว่าดีที่สุดมาใช้งาน</p><p>ที่อธิบายมาเนี่ย ผมจะไม่สอนในบทความนี้นะ!! คือแค่อยากบอกให้รู้ว่า Modelๆ นึง เนี่ยมันมีที่มานะ ไม่ได้เสกเอามั่วๆ 😄</p><p>การสร้างและฝึก Model เนี่ย จะใช้เวลาและทรัพยากรมาก ซึ่งโดยปกติแล้วจะทำกันบนคอมพิวเตอร์ ดังนั้นโค้ดที่เราจะเขียนลง iOS จะเป็นโค้ดส่วนของการนำ Model ที่ฝึกแล้วมาใช้งานซะมากกว่า</p><p>ดังนั้นไม่ต้องกังวล ถ้ายังไม่เข้าใจว่าจะสร้างและฝึก Model ยังไง เพราะในบทความนี้ โค้ดทั้งหมดจะเป็นโค้ดในส่วนของการนำ Model (ที่ถูกฝึกแล้ว) มาใช้งาน</p><h3>การนำ Model มาใช้งาน</h3><p>Model ของ Caffe 2 จะเป็นไฟล์ protocol buffer (.pb) ซึ่งข้างในก็มี definition ของโครงสร้าง และค่าของตัวแปรต่างๆ ที่จำเป็นต่อการใช้งาน</p><p>Caffe 2 มี Model สำเร็จรูป พร้อมใช้งาน ให้เลือกใช้มากมาย ที่ <a href="https://github.com/caffe2/caffe2/wiki/Model-Zoo">Model Zoo</a> แต่ละ Model จะบอกว่า รับ input อะไร และ output ที่ทำนายออกมาคืออะไร</p><p>สำหรับการเขียนแอพนี้ เราจะใช้ Model ที่ชื่อว่า Squeezenet ซึ่งเมื่อเราใส่ input คือรูปภาพเข้าไป ตัว Model จะทำนายว่ารูปนั้นเป็นรูปของอะไร โดยสามารถจำแนกรูปได้ 1000 ชนิด</p><h3>การติดตั้ง Caffe 2 และการนำมาใช้ใน Xcode</h3><p>สำหรับ การใช้งานใน Xcode นั้น ขั้นตอนแรกเราต้อง build library สำหรับ iOS โดยมีขั้นตอนดังนี้</p><ol><li>ลง cmake</li><li>clone Caffe 2 repository</li><li>build ไลบารี่ Caffe 2 สำหรับ iOS</li></ol><pre>brew install cmake<br>git clone --recursive <a href="https://github.com/caffe2/caffe2.git">https://github.com/caffe2/caffe2.git</a><br>cd caffe2 &amp;&amp; ./scripts/build_ios.sh</pre><p>เมื่อ build เสร็จแล้ว เราจะได้ ./build_ios โฟลเดอร์</p><p>***ไลบารี่ที่ build มานั้นจะเป็นไลบารี่สำหรับ cpu ประเภท arm ดังนั้นเราจะไม่สามารถใช้งานบน Simulator ได้ (ให้ต่อ iPhone/iPad และเลือก device จริงใน Xcode)</p><p>เปิด Xcode สร้างโปรเจค และ copy ไลบารี่ข้างล่างนี้มาไว้ในโฟลเดอร์เดียวกัน คือ ~/xcode_project_name/Frameworks/Caffe2 จากนั้นก็ลากไฟล์ไลบารี่เข้ามาใน Xcode</p><pre>./build_ios/caffe2/libCaffe2_CPU.a<br>./build_ios/libCAFFE2_NNPACK.a<br>./build_ios/libCAFFE2_PTHREADPOOL.a<br>./build_ios/third_party/protobuf/cmake/libprotobuf.a</pre><p>ใน Build Settings ของ Xcode เพิ่มค่า Library Search Paths ให้ชี้ไปที่โฟลเดอร์ที่รวมไลบารี่ที่เรา copy มา</p><pre>$(PROJECT_DIR)/Frameworks/Caffe2</pre><p>เพิ่มค่า Header Search Paths ให้ชี้ไปที่ โฟลเดอร์เหล่านี้ของ Caffe 2 (ผม copy caffe2 มาอยู่ที่เดียวกับ Xcode project)</p><pre>$(PROJECT_DIR)/caffe2<br>$(PROJECT_DIR)/caffe2/build_ios $(PROJECT_DIR)/caffe2/build_host_protoc/include $(PROJECT_DIR)/caffe2/third_party/eigen</pre><p>ใน Other Linker Flags ให้เพิ่ม ค่าเหล่านี้ ไม่งั้นรันแอพแล้วพังนะเออ</p><pre>-force_load<br>$(PROJECT_DIR)/Frameworks/Caffe2/libCaffe2_CPU.a</pre><p>ลองสร้าง Objective-C++ ไฟล์ขึ้นมา (สร้างคลาส Objective-C แล้วเปลี่ยนนามสกุล .m เป็น .mm) แล้วลองใส่บรรทัดนี้ ถ้า build ผ่านก็แสดงว่าเสร็จเรียบร้อย</p><pre>#import &quot;caffe2/core/predictor.h&quot;</pre><p>ยังไม่จบ !! ในการเขียนแอพนี้เราจะใช้ OpenCV ซึ่งเป็นไลบารี่ Image Processing ใช้เถอะ แล้วชีวิตเราจะสบาย</p><p>ดาวโหลด opencv-ios-framework.zip จากที่นี่ <a href="https://github.com/opencv/opencv/releases">github.com/opencv</a> แล้ว copy opencv2.framework มาที่ ~/xcode_project_name/Frameworks/ จากนั้นก็ลากไฟล์ เฟรมเวิร์คเข้ามาใน Xcode</p><p>ใน Framework Search Paths ให้เพิ่มค่านี้</p><pre>$(PROJECT_DIR)/Frameworks</pre><p>ทำการสร้าง Prefix Header File โดยไปที่ File-&gt;New-&gt;File...-&gt;PCH File แล้วใส่โค้ดนี้ลงไป เพื่อให้โค้ด Objective-C++ ของเราเห็นไลบารี่ของ OpenCV</p><pre>#ifdef __cplusplus<br>#import &lt;opencv2/opencv.hpp&gt;<br>#endif</pre><p>เสร็จละ 😀</p><h3>ลงมือเขียนโค้ด</h3><p>ผมจะพูดถึงโค้ด โดยเริ่มต้นที่ UIImage จนกระทั่งได้ผลลัพธ์การทำนายออกมาว่าเป็นรูปอะไร</p><p>โดยสรุป แบ่งเป็นสิ่งหลักๆ ที่ต้องทำ ดังนี้</p><ol><li>โหลด Model เข้ามาใช้งาน</li><li>แปลงภาพ เป็น input เพื่อนำไปป้อนให้กับ Model</li><li>ป้อน input ให้กับ Model และทำนายผลลัพธ์</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGHS8DvHb0lGSEsdJpZP1Q.png" /><figcaption>แผนภาพของงานโดยรวม</figcaption></figure><h3>1. โหลด Model</h3><p>โดยปกติ Caffe 2 Model จะมีอยู่สองไฟล์คือ exec_net.pb และ predict_net.pb <br>สามารถไปดาวน์โหลด SqueezeNet Model ได้ที่นี่ <a href="https://github.com/caffe2/models/tree/master/squeezenet">https://github.com/caffe2/models/tree/master/squeezenet</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*czkzL7KSLY6vZ6_11IpEIg.png" /></figure><p>ในโค้ดส่วนแรก จะเป็นฟังก์ชันเพื่อโหลดข้อมูลของไฟล์โมเดล .pb เข้ามาเก็บไว้ใน caffe2::Netdef</p><pre>#import &quot;caffe2/core/predictor.h&quot;<br>#import &quot;caffe2/utils/proto_utils.h&quot;</pre><pre>// C++ function<br><br>void LoadPBFile(NSString *filePath, caffe2::NetDef *net) {<br>    NSURL *netURL = [NSURL fileURLWithPath:filePath];<br>    NSData *data = [NSData dataWithContentsOfURL:netURL];<br>    const void *buffer = data.bytes;<br>    int len = (int)data.length;<br>    CAFFE_ENFORCE(net-&gt;ParseFromArray(buffer, len));<br>}</pre><p>ทำการสร้าง caffe2::Predictor จาก caffe2::Netdef ที่เราโหลดเรียบร้อยแล้ว</p><pre>-(void)initPredictor {<br>    NSString *init_net_path = [NSBundle.mainBundle pathForResource:@&quot;exec_net&quot; ofType:@&quot;pb&quot;];</pre><pre>    NSString *predict_net_path = [NSBundle.mainBundle pathForResource:@&quot;predict_net&quot; ofType:@&quot;pb&quot;];</pre><pre>    caffe2::NetDef init_net, predict_net;<br>    LoadPBFile(init_net_path, &amp;init_net);<br>    LoadPBFile(predict_net_path, &amp;predict_net);</pre><pre>    auto predictor = std::make_unique&lt;caffe2::Predictor&gt;(init_net, predict_net);<br>}</pre><p>เมื่อเสร็จขั้นตอนนี้เราจะได้ caffe2::Predictor ที่พร้อมให้เราป้อน input</p><h3>2. แปลงภาพให้เป็น input ที่เหมาะสม</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*1-oZdS65EXbEvIBbQPc0Jw.png" /></figure><p>สำหรับ input ของ SqueezeNet Model จะต้องเป็นข้อมูลของภาพ BGR ขนาด 227 x 227 ที่มีโครงสร้างแบบ NCHW (จะอธิบายต่อข้างล่างว่ามันคือไร)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*RM1r4kuE7P6wmO9yfmjhkw.png" /><figcaption>HWC vs CHW</figcaption></figure><p>โดยวิธีแบบชาวบ้านๆ ข้อมูลของภาพ BGR 1 ภาพ จะถูกเก็บไว้ใน array ที่มีขนาดเท่ากับ height x width x channels ในทีนี้คือ</p><pre>float hwc_input[227][227][3]; </pre><pre>// height   = 227<br>// width    = 227<br>// channels = 3 (BGR)</pre><p>ถ้าเราต้องการค่าสีทั้งสามสีที่ตำแหน่ง (row, col) เราสามารถดึงค่าได้ แบบนี้</p><pre>float blue  = hwc_input[row][col][0]<br>float green = hwc_input[row][col][1]<br>float red   = hwc_input[row][col][2]</pre><p>เราจะเรียก input แบบนี้ว่า HWC</p><p>….แต่เนื่องจาก Caffe 2 พี่แกเล่นท่ายากครับ (เค้ามีเหตุผลของเค้า) พี่แกใช้ CHW แทนครับ ดังนั้น ข้อมูลของภาพที่เราต้องเตรียมให้กับ Model จะเป็นลักษณะแบบนี้</p><pre>float chw_input[3][227][227];</pre><pre>// channels = 3 (BGR)<br>// height   = 227<br>// width    = 227</pre><p>วิธีการดึงค่าสีที่ตำแหน่ง (row, col) ก็จะต่างกันแบบนี้</p><pre>float blue  = chw_input[0][row][col]<br>float green = chw_input[1][row][col]<br>float red   = chw_input[2][row][col]</pre><p>ดังนั้นเมื่อเราได้ข้อมูลของภาพ BGR มา เราจะต้องเปลี่ยนโครงสร้างของข้อมูลนิดหน่อย ที่ปกติเป็น HWC ให้กลายเป็น CHW</p><p>แต่สิ่งที่เราต้องการคือ NCHW นิ แล้ว N คืออะไร ? N คือจำนวนของภาพครับ บาง Model ต้องการ input ที่เป็นภาพหลายๆภาพ พร้อมๆกัน N ก็จะต่างกันไปครับ แต่สำหรับ SqueezeNet จะใช้แค่ภาพเดียว ดังนั้น N = 1</p><p>โดยสรุป โครงสร้างของ input สำหรับ SqueezeNet ก็คือ</p><pre>float nchw_input[1][3][227][227]</pre><pre>// number_of_images = 1<br>// channels         = 3 (BGR)<br>// height           = 227<br>// width            = 227</pre><p>รู้คอนเซปต์คร่าวๆ กันไปแล้ว ลงมือทำกันเลย</p><p><strong>เริ่มต้นที่ Daisy</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*g5mphqmfMU-L0Umil2L9dg.jpeg" /><figcaption>รูปดอกเดซี่</figcaption></figure><p>รูปนี้จะเป็น input ตั้งต้น ของโค้ดที่เราจะเขียน</p><p><strong>2.1 แปลง </strong><strong>UIImage เป็น BGR </strong><strong>cv::Mat</strong></p><p>cv::Mat คือ matrix ที่เก็บข้อมูลของภาพภาพนึง</p><p>เนื่องจากข้อมูลรูปภาพที่อยู่ใน UIImage จะถูกเก็บในรูปแบบ RGBA ดังนั้นขั้นตอนแรกคือสร้าง RGBA cv::Mat จาก UIImage ได้ดังนี้</p><pre>UIImage *daisy = [UIImage imageNamed:@&quot;daisy&quot;];<br>cv::Mat daisy = [daisy cvMatRGBA];</pre><p>เมื่อเรามี RGBA cv::Mat เราก็สามารถแปลงเป็น BGR cv::Mat ได้ง่ายๆ อย่างนี้เลย</p><pre>- (cv::Mat)cvMatBGR {<br>    cv::Mat result = [self cvMatRGBA];<br>    cv::cvtColor(result, result, CV_RGBA2BGR);<br>    return result;<br>}</pre><pre>// Usage<br>UIImage *daisy = [UIImage imageNamed:@&quot;daisy&quot;];<br>cv::Mat daisy_bgr = [daisy cvMatBGR];</pre><p>ผลลัพธ์ แสดงได้เป็นภาพตามนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*KlyKeFncV_cY3KyxmyOBUQ.png" /></figure><p><strong>2.2 ย่อภาพให้มีขนาด 227 x 227</strong></p><pre>cv::Mat resized_hwc;<br>cv::resize(daisy_bgr, resized_hwc, cv::Size(227, 227));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*6liox41ATHnmNBUWcOlZCA.png" /></figure><p><strong>2.3 แปลง HWC เป็น NCHW</strong></p><pre>float chw_input[3][227][227];</pre><pre>for (auto row = 0; row &lt; 227; ++row) {<br>  for (auto col = 0; col &lt; 227; ++col) {<br>    auto pixel = resized_hwc.at&lt;cv::Vec3b&gt;(row, col);<br>    chw_input[0][row][col] = (float) pixel[0];<br>    chw_input[1][row][col] = (float) pixel[1];<br>    chw_input[2][row][col] = (float) pixel[2];<br>  }<br>}</pre><p>เราจะได้ chw_input ที่เป็น float array 3 มิติ ที่มีขนาด [C][H][W] แต่ก่อนที่เราจะป้อนให้ Model เนี่ย เราต้องแปลงให้เป็น vector&lt;float&gt; ที่มีขนาด CxHxW ซะก่อน</p><pre>auto data_begin = std::begin(chw_input[0][0]);<br>auto data_end = std::end(chw_input[2][226]);</pre><pre>// NCHW 1D vector<br>std::vector&lt;float&gt; inputPlanar(data_begin, data_end);</pre><p>สรุปสิ่งที่เราได้ทำลงไป ตั้งแต่ UIImage จนเป็นกลายเป็น inputPlanar</p><pre>UIImage *daisy<br>      ↓<br>cv::Mat daisy_bgr<br>      ↓<br>cv::Mat resized_hwc<br>      ↓<br>float chw_input[c][h][w]<br>      ↓<br>vector&lt;float&gt; nchw_input_planar</pre><h3>3. ป้อน input และทำนายผลลัพธ์</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*YtQ9zmt9NRj9jB2WH9fs7w.png" /></figure><p>ง่ายมาก มีโค้ดแค่นี้เอง</p><pre>caffe2::TensorCPU input;<br>// { N, C, H, W }<br>input.Resize(std::vector&lt;int&gt;({ 1, 3, 227, 227 }));<br>input.ShareExternalPointer&lt;float&gt;(inputPlanar.data());</pre><pre>caffe2::Predictor::TensorVector input_vec{ &amp;input };<br>caffe2::Predictor::TensorVector output_vec;</pre><pre>predictor-&gt;run(input_vec, &amp;output_vec);</pre><p>เราจะได้ output ออกมา โดยขึ้นอยู่กับแต่ละ Model ที่เราเอามาใช้ ว่าจะออกมาในรูปแบบไหน สำหรับ SqueezeNet จะให้ output ออกมาเป็น vector&lt;float&gt; ขนาด 1000 ซึ่งแต่ละค่าจะแทน ค่าความน่าจะเป็นที่รูปนั้นจะอยู่ในประเภทเดียวกับ ImageNet class ในตำแหน่งเดียวกัน</p><p>สามารถดู ImageNet class ได้ที่นี่ <a href="https://github.com/nRewik/caffe2-ios-sample/blob/master/caffe2-ios-sample/Deep%20Learning/imagenet_classes.json">imagenet_classes.json</a></p><pre>NSMutableArray&lt;Prediction *&gt; *results = [NSMutableArray new];</pre><pre>auto output = output_vec[0];<br>for (auto index = 0; index &lt; output-&gt;size(); index++) {<br>  auto vals = (const float *)output-&gt;raw_data();<br>  auto val = vals[index];<br>  NSString *itemName = [Prediction itemNameForClassIndex:index];<br>  Prediction *prediction = [[Prediction alloc]<br>  initWithItemName:itemName confidence:val];<br>  [results addObject:prediction];<br>}</pre><p>สุดท้ายแล้ว เราก็จะได้ผลลัพธ์ของการทำนาย และนี่ก็คือผลลัพธ์สุดท้ายที่เราได้มา (เลือกโชว์ 5 ค่า ที่มากที่สุด)</p><pre><strong>Top Five Predictions</strong></pre><pre><strong>0.955403625965118 daisy<br>0.0275774486362934 cardoon<br>0.0156224304810166 bee<br>0.00033232313580811 pot, flowerpot<br>0.0002196237037424 sulphur butterfly, sulfur butterfly</strong></pre><h3>ทิ้งท้าย</h3><p>สิ่งที่เราได้จากบทความนี้ จะเป็น workflow ส่วนของการนำ Model สำเร็จรูปมาใช้งาน ซึ่งจริงๆแล้ว เราแทบไม่ต้องรู้อะไรเกี่ยวกับ Deep Learning เลยก็ได้(มั้ง?) เราไม่จำเป็นต้องรู้ว่าข้างในมันทำงานยังไง สิ่งที่เรารู้มีเพียงแค่ เตรียม input อะไร และรับ output ยังไง</p><p>ที่ผ่านมาผมคิดว่า Machine Learning เป็นเรื่องที่จับต้องยาก มีคณิตศาสตร์มากมายเต็มไปหมด การจะเอาเข้ามาใช้ในแอพ ต้องมีความรู้ ความเข้าใจ ใช้เวลาศึกษากันหลายเดือน</p><p>แต่จากที่ผมได้ทำ side project ทำให้รู้ว่า จริงๆแล้ว มันมีการแบ่ง workflow ที่ชัดเจน ประมาณว่า การสร้างและฝึก Model ก็ให้คนที่เชี่ยวชาญเช่น Data Scientist ทำไป ส่วนเรา Software Engineer ก็แค่เอา Model ที่เสร็จแล้วมาประกอบเข้าในแอพ</p><p>ซึ่งเฟรมเวิร์คต่างๆตอนนี้ ก็สะดวกต่อการใช้งานมากขึ้น ดังนั้นการที่เราจะฝัง AI ลงในแอพ เพื่อรองรับงานประเภท on-device processing ก็เป็นเรื่องที่จับต้องได้มากขึ้น</p><p><strong>ข้อมูลอ้างอิง</strong></p><ul><li><a href="https://caffe2.ai/">caffe2.ai</a></li><li><a href="https://code.facebook.com/posts/196146247499076/delivering-real-time-ai-in-the-palm-of-your-hand/">Delivering real-time AI in the palm of your hand</a></li><li><a href="http://jamesonquave.com/blog/caffe2-on-ios-deep-learning-tutorial/">Caffe2 in an iOS App — Deep Learning Tutorial</a></li></ul><p>ถ้าชอบกด like ถ้าใช่กด share มีคำถาม, ข้อสงสัย หรือคำชี้แนะ สามารถโพสคอมเม้นต์ได้เลยครับ</p><p>Nutchaphon Rewik—iOS Engineer </p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22e26dde1fb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[30 Months as an iOS engineer. My tips for newcomers.]]></title>
            <link>https://medium.com/@nrewik/18-months-as-an-ios-developer-my-tips-for-newcomers-107f76db3550?source=rss-b75c758c5100------2</link>
            <guid isPermaLink="false">https://medium.com/p/107f76db3550</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nutchaphon Rewik]]></dc:creator>
            <pubDate>Fri, 12 Aug 2016 06:35:38 GMT</pubDate>
            <atom:updated>2017-02-08T15:05:53.113Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVHh3QVSTaMj79izjiEaTw.jpeg" /></figure><ul><li>30 months</li><li>7 apps</li><li>2 big apps</li><li>A part-time freelance</li><li>A full-time iOS engineer</li><li>A long-time gamer</li></ul><p>Here are my iOS development tips for newcomers.</p><h3>Take Swift</h3><p>Swift vs Obj-C which one should I learn first? My answer is directly toward Swift. Learn, Play and Start your new project with Swift. Unless you have a good reason for Obj-C. For example, maintaining the old app.</p><p>Warning—Don’t plan to start your project in Obj-C and migrate to Swift later. The migration is harder than you think.</p><h3>Know Ecosystem</h3><p>What is the popular JSON library? Which cloud database should I use with my app? What’s going on currently?</p><p>You should know tool/library/framework/stack for your app. Don’t be a lone programmer, and write everything yourself. Somebody already contributed those works to make your life easier. Pick and use them to increase productivity.</p><p>For open-source libraries. Search `<em>awesome-xxx`.</em> For example, `<em>awesome-swift</em>`, `<em>awesome-ios</em>`.</p><h3>Make it work, Make it right, Make it fast</h3><p>I always believe this concept. Software development is not a one-time work. Good softwares are crafted through many iterations. When you first make something, it might not be good as you think. But don’t worry, take time and revisit it again, and make it better. Just remember what you were doing. Experiences will help you. Going to the last step in the next times is easier than you think.</p><h3>Learn Architecture</h3><p>Take a look at other successful apps. See how they were made. Not only the app side, but the entire system. Architectural perspective will improve your craftsmanship. There are many open-source iOS apps out there. Telegram, Firefox, Wikipedia, Wordpress, VLC, Wire. <a href="https://github.com/dkhamsing/open-source-ios-apps">github/open-source-ios-apps</a> is a good resource.</p><h3>Experiment</h3><p>When developing an app. You may come up with many ideas. Sometimes you are not sure whether they will work or not. So, make a proof of concept first. Express your ideas with side projects. If it works, then move it to your main project.</p><p>If they are small code level. Don’t wasting your time compiling and running the whole project. Write and test it on Playground. See the results, then copy&amp;paste.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*gEy57j5IEWd11q_HJHI5lA.png" /><figcaption>My.playground</figcaption></figure><h3>Don’t fight the framework</h3><p>Reactive, Redux are good frameworks to learn. Learning them will definitely help you to become a good developer. But don’t use them as a main framework in a big iOS app. I’ve tried and it just doesn’t work for me. I always face the problem. And solving that problem is not an easy task. So, stay close to MVC/MVVM.</p><p>Use those frameworks as helper tools, and only when they make your life easier. For example, I use Reactive for event handling.</p><h3>Functional Programming is f**king good</h3><p>Immutability. Pure function. Higher-order function. Many concepts of functional programming will greatly improve your understanding. Even if you don’t aim to use it in iOS development. Believe me, just learn it.</p><h3>Best practice is quite the dream</h3><p>Everything has its trade-off. You cannot always follow those guidelines that might exist only in textbooks. Practicality and improvisation will help you to survive.</p><h3>Keep yourself up-to-date</h3><p>Technology grows exponentially. Stay still for a year and you will become a wise monkey. Update your database every week if possible. Weekly email subscription is my preference. <a href="https://iosdevweekly.com/">iOS dev weekly</a>, <a href="http://ios-goodies.com/">iOS goodies</a>, <a href="https://www.natashatherobot.com/">Natasha The Robot</a>, <a href="https://littlebitesofcocoa.com/">little bite of cocoa</a>. This way I don’t have to find those curated sources myself. Just having a good time reading them on weekend.</p><p>…and watch WWDC .</p><h3>Learn something else</h3><p>Swift/Obj-C/iOS. What else? Many. Try to get your hand dirty with something else. Backend, Web, Game. Sick of programming? Design and Business may be. You can never go wrong with your choices.</p><p>Thank you for reading. Hope you enjoy. 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=107f76db3550" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy Line Drawing Animation]]></title>
            <link>https://medium.com/@nrewik/easy-line-drawing-animation-b56958bc2bee?source=rss-b75c758c5100------2</link>
            <guid isPermaLink="false">https://medium.com/p/b56958bc2bee</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Nutchaphon Rewik]]></dc:creator>
            <pubDate>Fri, 01 Jan 2016 13:04:44 GMT</pubDate>
            <atom:updated>2016-01-01T13:11:39.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*jobmozxtI_w8QfM4Y7jwtg.gif" /></figure><p>In iOS, We can create line drawing animation with CAShapeLayer’s <em>.strokeStart</em> and <em>.strokeEnd</em> properties.</p><p>It is pretty straightforward. First we need to create a path.</p><pre>let bezierPath = UIBezierPath()</pre><pre>/* draw code goes here*/<br>bezierPath.addArcWithCenter( arcCenter, <br>    radius: 50.0, <br>    startAngle: 0, <br>    endAngle: CGFloat( 2 * M_PI ), <br>    clockwise: true )</pre><pre>/* assign a path to CAShapeLayer */<br>shapeLayer.path = bezierPath.CGPath</pre><p>Then animate <em>.strokeStart</em> or <em>.strokeEnd </em>properties.</p><pre>let animation = CABasicAnimation(keyPath: “strokeEnd”)</pre><pre>/* set up animation */<br>animation.fromValue = 0.0<br>animation.toValue = 1.0<br>animation.duration = 2.5</pre><pre>shapeLayer.addAnimation(animation, forKey: “drawLineAnimation”)</pre><p>And, we’re done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*eo8F8unRbI9yf4y2z1EUDg.gif" /><figcaption>Line Drawing Animation</figcaption></figure><p>Try experiment, we can make another nice progress ring animation with a few lines of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*2-1s7Zksm84lk5yq2FHXrA.gif" /><figcaption>Progress Ring Animation</figcaption></figure><p>Easy right? The only thing that would be difficult is drawing a complex bezier path. So, you might take a look at <a href="http://www.paintcodeapp.com/">PaintCode</a>, which you can draw bezier path by hand. This app will generate code from your drawing—ready for copy&amp;paste to Xcode.</p><blockquote>Pro tip, we can import an existing SVG.</blockquote><p>The Xcode project can be found at <a href="https://github.com/nRewik/EasyLineDrawingAnimation">nRewik/EasyLineDrawingAnimation</a>.</p><h4><em>Happy New Year 2016 🎅🎄. If you liked this post please recommend and share to your friends. Thanks.</em></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b56958bc2bee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy Animation with UIStackView]]></title>
            <link>https://medium.com/@nrewik/easy-animation-with-uistackview-8878b2856ae2?source=rss-b75c758c5100------2</link>
            <guid isPermaLink="false">https://medium.com/p/8878b2856ae2</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Nutchaphon Rewik]]></dc:creator>
            <pubDate>Sat, 26 Sep 2015 14:10:44 GMT</pubDate>
            <atom:updated>2015-09-27T01:37:55.749Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>UIStackView</strong> leverages the power of Auto Layout by managing the layout of all the views inside. You can change property of UIStackView or its arranged subview, and place these changes inside an animation block.</p><p>For example, changing <strong>hidden</strong> property of the arranged subview.</p><pre>UIView.animateWithDuration(0.3){<br>    viewInsideStackView.hidden = true //or false<br>}</pre><p>Here’s the animation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*2GD8nqR29C1eMLWKDd0c2g.gif" /></figure><p>iOS encourages you to create adaptive UI, when working with <strong>UIStackView</strong>, you can define size-class specific values for many of the stack view’s properties directly in Interface Builder. <strong>UIStackView</strong> automatically animates these changes for you.</p><p>For example, changing <strong>axis</strong> property of <strong>UIStackView</strong> in <strong>CompactHeight</strong>, and with some tweaks of the arranged subview’s constraints. You can have this animation without coding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*dEwoYVDVNxgpYpv6V3uccQ.gif" /></figure><p>For the detail of how constraints are set up, see the full project at GitHub <a href="https://github.com/nRewik/UIStackViewEasyAnimation">UIStackViewEasyAnimation</a></p><h3>References</h3><p><a href="https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIStackView_Class_Reference/">UIStackView</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8878b2856ae2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chaining Async Requests in iOS]]></title>
            <link>https://medium.com/@nrewik/chaining-async-requests-in-ios-b492ad9d9b4a?source=rss-b75c758c5100------2</link>
            <guid isPermaLink="false">https://medium.com/p/b492ad9d9b4a</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nutchaphon Rewik]]></dc:creator>
            <pubDate>Fri, 11 Sep 2015 00:57:25 GMT</pubDate>
            <atom:updated>2015-09-11T13:20:51.467Z</atom:updated>
            <content:encoded><![CDATA[<p><em>TL;DR callback, delegate and </em><strong><em>promise</em></strong></p><p>We use asynchronous request to get data somewhere on Internet. A single request is very easy to handle.</p><p>Here comes the tough time, dealing with multiple async requests. Especially, when they have dependency between each other like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*LOtVkRWlAI-y-RKSwnp-yQ.png" /></figure><p>In this article, I will show the ways to perform http request chaining in iOS. I will use the <strong>GetAddressesOperation </strong>as an example. This operation has three subtasks as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*qdB0nyxoB5AaPLVFV6Vhng.png" /></figure><h3><strong>Callback</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42a07e82d21fd53716d60cbfc80e0f2a/href">https://medium.com/media/42a07e82d21fd53716d60cbfc80e0f2a/href</a></iframe><p>Callback function is a classic pattern in async. Invoke <strong>NSURLSessionTask</strong>,<strong> </strong>after the task is finished, the completion block will be called. At this point, we have the result, then we call the next request in the chain.</p><p>Horrible code makes you mad, It is hurting your eyes. Whenever you read this code, you’re stacking your thought like pyramid. This push-to-right code is called Pyramid of doom, or spaghetti code.</p><p>Besides ugliness, the code leads to bug. Consider variable scope, when you write the deepest last request, you may accidentally use variable from outer scope and break encapsulations, causing logic errors at worst.</p><p>I have no problem with three requests, but real world is so cruel. It’s not just three. If the backend guy insists on giving an easy API. You might have to deal with a horde.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*V9YHWEDsh9VzPyJ17ApGyg.png" /></figure><h3>Delegate</h3><p>Unless we specify a completion block, <strong>NSURLSession</strong> will call delegate function instead. (See full code at <a href="https://gist.github.com/nRewik/f72cbc7e087c447421da">Gist</a>.)</p><p>It looks like a black hole. You manage everything inside a delegate function, including, order requests, concatenate data, handle error and parse result. For all requests in one place, Ah that’s a lot. (@_@)</p><p>Delegate pattern flattens async blocks, and It’s too flat! It leaves code flow in imagination. Unless I comment the code, it looks unclear what the order that I am now.</p><p>Variable scope puzzlement. Variables are all in the same place, you might mess up something unintentionally, and that raise debug/test difficulty +10 levels.</p><p>However, in case I really need to do something advance such as, tracking progress, dealing with background, handling auth challenge, working with stream, etc. Delegate would be my first choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*Kv6SCSVl3PsyDfXe4RAoEQ.png" /></figure><h3>Promise</h3><p>Despite the previous two iOS citizens, Promise is a pattern from else where. It has been developing as a core feature in many languages. However, Swift hasn’t got one.</p><p>Fortunately, we don’t have to reinvent the wheel. Thanks to <a href="http://promisekit.org/">PromiseKit</a>, an astounding lib that I will be using to defeat this async boss.</p><p>Here’s the code that use Promise pattern.</p><pre>firstly{<br>    self.getToken()<br>}<br>.then{ token in<br>    self.getUserData(token: token)<br>}<br>.then{ userData in<br>    self.getAddresses(userID: userID)<br>}<br>.then{ addresses in<br>    println(&quot;done&quot;)<br>}<br>.catch{ error in<br>    println(error)<br>}</pre><p>Promise eliminates spaghetti code, breaks indentations, refactors code in synchronous manner. The code looks cleaner, and more readable. You can try to read code to your friends, and they will suddenly know what you have done.</p><p>Chaining async is very easy in Promise. We specify `<strong>then`</strong> handler at the end of Promise, any subsequent `<strong>then` </strong>will wait on the previous promise’s resolution before continuing.</p><p>Error handling is the most thing I like. When any Promise thrown an error, the chain will stop, and this is your chance to `<strong>catch</strong>` an error.</p><p>We create an async task with <strong>Promise&lt;T&gt;</strong>.<strong> </strong>This type tells us that it might produce <strong>T</strong> of a given future (<strong>fulfill</strong>), or throw an error (<strong>reject</strong>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5ecb0838eac9b3af4b66ea9028fa265/href">https://medium.com/media/a5ecb0838eac9b3af4b66ea9028fa265/href</a></iframe><h3>Summary</h3><p>We can handle multiple async requests using callback, delegate and Promise pattern. In my opinion, I would recommend Promise. However, I cannot give a verdict on what is the best. It depends on the situation, and there are other interesting patterns that I didn’t mention here. So, choose what you like, and be happy to live in the world of asynchrony :)</p><h4>References</h4><ul><li><a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165-BCICJDHA">URL Loading System Programming Guide</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise in JavaScript</a></li><li><a href="http://promisekit.org/">PromiseKit</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b492ad9d9b4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Animation with
Auto Layout]]></title>
            <link>https://medium.com/@nrewik/animation-with-auto-layout-dfe87745ab12?source=rss-b75c758c5100------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfe87745ab12</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[autolayout]]></category>
            <dc:creator><![CDATA[Nutchaphon Rewik]]></dc:creator>
            <pubDate>Fri, 17 Jul 2015 18:45:58 GMT</pubDate>
            <atom:updated>2015-07-18T12:00:34.376Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*bsc6wCWh0sqlhGKNcFJ_mw.png" /></figure><p>Auto Layout is a powerful feature. It manages the position and size of the views. Basically, we create constraints, Auto Layout will automatically adjust the views to satisfy all constraints.</p><h3>Animation</h3><p>Auto Layout animation can be achieved by changing constraint property, and then tell Auto Layout that constraint property is updated, please adjust the views to satisfy new constraint property</p><p>The code will look like this.</p><pre>constraint.constant = someValue //change constraint&#39;s property<br>UIView.animateWithDuration(0.3){<br>     self.view.layoutIfNeeded() //tell the view to layout again<br>}</pre><p>For example, I create a width constraint to the view. When I press the button, the view will expand and shrink back and forth.</p><pre>@IBOutlet weak var widthConstraint: NSLayoutConstraint!<br>var selected = false</pre><pre>@IBAction func switchButtonPressed() {<br>    selected = !selected<br>    widthConstraint.constant = selected ? 100 : 200<br>    UIView.animateWithDuration(0.3){<br>        self.view.layoutIfNeeded()<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*fFG9YYcSQtxDQU1l0-5lDA.gif" /></figure><p>In the code, we saw <strong>widthConstraint</strong> is an<strong> @IBOutlet</strong>. That means we can setup the constraint in <strong>Interface Builder</strong>, and then link it by <strong>ctrl+drag </strong>into code.</p><h3>Real App Animation</h3><p>Easy right ? Now, let’s make an animation, which we would make it into the real app. Like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*7hR0eoJGfQBwF9nngEcmYA.gif" /></figure><p>How to achieve this ? Without Auto Layout, you might calculate <strong>tableView</strong> frame and check the boundary, I’m sure that it will take more than 10 lines of codes to maintain the positions and sizes.</p><p>With Auto Layout. we can achieve this with just these lines of codes. ( see completed project on <a href="https://github.com/nRewik/AutoLayoutAnimation">Github</a>)</p><pre>tableViewHeightConstraint.constant = tableView.contentSize.height<br>UIView.animateWithDuration(0.3){<br>    self.view.layoutIfNeeded()<br>}</pre><p>Why so short? because, we’ve left other works to Auto Layout in Interface Builder by making these vertical constraints:</p><pre><strong>//Vertical Constraints</strong></pre><pre>1. <strong>middleView</strong> height = 80<br>2. <strong>middleView</strong> top space to <strong>tableView</strong> = 0<br>3. <strong>middleView</strong> bottom space to <strong>bottomView </strong>&gt;= 0</pre><pre>4. <strong>bottomView </strong>height = 80<br>5. <strong>bottomView </strong>bottom space to <strong>bottom layout guide</strong> = 0</pre><pre>6. <strong>tableView</strong> height = 100, <em>priority = 999</em><br>7. <strong>tableView </strong>top space to <strong>top layout guide</strong> = 0</pre><p>Basically, whenever <strong>tableViewHeightConstraint </strong>is updated, Auto Layout will also adjust the position of <strong>middleView.</strong></p><p>Someone might ask. Will it break? If I set the tableView height to 99999, so Auto Layout will not be able to satisfy the constraints. The answer is no. Although, you can set whatever you like, Auto Layout will ignore this constraint.</p><p>Ignore? yes, because <strong>IB</strong> set constraint’s priority to 1000 by default. 1000 means the constraint must be satisfied. Whatever below 1000 means if the constraint can’t be satisfied, then just ignore it.</p><p>So, we set <strong>tableViewHeightConstraint’s </strong>priority to be less than 1000. This causes Auto Layout to adjust views’ position<strong> </strong>before <strong>tableView’s </strong>height, and when <strong>tableView’s </strong>height exceeds the boundary, the constraint will be ignored.</p><h3>Another Example</h3><p>In this case, I have three views. Left, middle and right. I want the behaviour that right view will move closer to left view when middle view is hidden.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*XLMfpVOqTtMrI2Jxdqi81g.gif" /></figure><pre>if selected{<br>    greenViewWidthConstraint.constant = 0<br>    greenGreyHorizontalSpaceConstraint.active = false<br>}else{<br>    greenViewWidthConstraint.constant = 75<br>    greenGreyHorizontalSpaceConstraint.active = true<br>}<br>UIView.animateWithDuration(0.3){<br>    self.view.layoutIfNeeded()<br>}</pre><p>In the code, I use another constraint’s property to animate Auto Layout. .<strong>active </strong>tell Auto Layout whether the constraint will be calculated or not.</p><p>These are constraints that I setup in IB.</p><pre><strong>//Horizontal Constraint</strong></pre><pre>1. <strong>redButton</strong> width = 75<br>2. <strong>redButton</strong> leading space to <strong>superView</strong> = 15<br>3. <strong>redButton </strong>trailing space to<strong> greenView</strong> = 15</pre><pre>4. <strong>greenView</strong> width = 75<br>5. <strong>greenView</strong> leading space to <strong>redButton</strong> = 15<br>6. <strong>greenView </strong>trailing space to<strong> greyView </strong>= 15</pre><pre>7. <strong>greyView</strong> leading space to <strong>greenView</strong> = 15<br>8. <strong>greyView </strong>trailing space to<strong> superView</strong> = 15</pre><pre>9. <strong>redButton </strong>trailing space to <strong>greyView </strong>= 15, <em>priority = 999</em></pre><h3>Summary</h3><p>We can make animation with Auto Layout by changing constraint property. Auto Layout preserves constraints, even when screen size is changed, or rotated. This ensures that you will get consistent layouts in all screen. So, let Auto Layout do its works, and cheers !!</p><p>See completed project on <a href="https://github.com/nRewik/AutoLayoutAnimation">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfe87745ab12" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>