tag:blogger.com,1999:blog-69121061567206881312024-03-14T04:00:36.016-07:00Coding for BugsAnonymoushttp://www.blogger.com/profile/03540465319086699554noreply@blogger.comBlogger7125tag:blogger.com,1999:blog-6912106156720688131.post-27200853630242225502014-06-29T11:32:00.000-07:002014-07-31T22:20:37.477-07:00Programming in Swift [Basic]<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="font-family: Arial, Helvetica, sans-serif;">Swift is a new programming language introduce by Apple at WWDC 2014. This language supports iOS7+ and you can integrate Swift with Objective-C and vice versa. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">I am covering Swift in three parts: Basic, Intermediate, and Advance. </span><span style="font-family: Arial, Helvetica, sans-serif;"> This post is all about basic of Swift Programming language. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">Its a brand new language and to learn this you don't require prior knowledge of Objective-C, but basics knowledge of C programming and Object Oriented Programming required. To execute Swift code you need latest version of development IDE (<span style="color: red;">Xcode 6</span>).</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<br />
<h3>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="color: #b45f06; font-size: large;">Playground</span></span></h3>
<span style="font-family: Arial, Helvetica, sans-serif;"> We are going to use new document type ".playground" to experiment with Swift. Its supported by Xcode 6. </span><span style="font-family: Arial, Helvetica, sans-serif;">Playground allow you to write/edit the swift code and see the result immediately side by side. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">Xcode create a playground for cocoa by default, you can create iOS playground through </span><b style="font-family: Arial, Helvetica, sans-serif;"><u>File --> New --> File --> iOS/Source/Playground.</u></b><span style="font-family: Arial, Helvetica, sans-serif;"> Cheers!! now you have a playground to play with Swift. Playground comes with some default code, it saying Hello playground, now delete the line starting with var keyword, We will discuss var latter in this tutorial. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">As usual say "Hello" to playground by printing a string. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #d12f1b}
span.s1 {color: #3d1d81}
span.s2 {color: #000000}
</style>
<br />
<div class="p1">
<span class="s1"> println</span><span class="s2">(</span>"Hello Playground"<span class="s2">)</span></div>
<div class="p1">
<span class="s2"><br /></span></div>
</div>
<br />
<span style="font-family: Arial, Helvetica, sans-serif;">Can you see the "Hello Playground" message in right pan? No right!! Okay so to see the result, you need to open the console output pan <b><u>(View --> Assistant Editor --> Show Assistant Editor)</u></b>. In third pan you can see the "Hello Playground" message. Okay! so what is the use of second pan? It shows value of variables and expressions. So whatever you print or draw comes under console pan.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<br />
<h3 style="text-align: left;">
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="color: #b45f06; font-size: large;">Constants & </span></span><span style="color: #b45f06; font-family: Arial, Helvetica, sans-serif; font-size: large;">Variables</span></h3>
<span style="font-family: Arial, Helvetica, sans-serif;"> You can use "</span><span style="font-family: Courier New, Courier, monospace;">let</span><span style="font-family: Arial, Helvetica, sans-serif;">" keyword to create constants and "</span><span style="font-family: Courier New, Courier, monospace;">var</span><span style="font-family: Arial, Helvetica, sans-serif;">" keyword to create variables. I have created two variables below :</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></div>
<div style="border-color: green; border-style: groove; border-width: 4px;">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #008400}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; min-height: 16.0px}
p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #d12f1b}
span.s1 {color: #bb2ca2}
span.s2 {color: #272ad8}
span.s3 {color: #008400}
span.s4 {color: #000000}
</style>
<br />
<div class="p1">
//constant<span class="Apple-converted-space"> </span></div>
<div class="p2">
<span class="s1"> let</span> minimumPrice = <span class="s2">18.5</span><span class="s3">//Double type</span></div>
<div class="p3">
<br /></div>
<div class="p1">
//Variables</div>
<div class="p2">
<span class="s1"> var</span> myVariable = <span class="s2">42</span> <span class="s3">// Inter type</span></div>
<div class="p4">
<span class="s1"> var</span><span class="s4"> blogName = </span>"Coding for Bugs"<span class="s4"> </span><span class="s3">//String type</span></div>
<div class="p4">
<span class="s3"><br /></span></div>
</div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">You have just created one constant as "</span>minimumPrice<span style="font-family: Arial, Helvetica, sans-serif;">" and two variables: "</span>myVariable"<span style="font-family: Arial, Helvetica, sans-serif;"> is of type Integer and "</span>blogName"<span style="font-family: Arial, Helvetica, sans-serif;"> is of type String. Wait we have not given any type, how swift is deciding the type of variable? Okay so </span><u style="font-family: Arial, Helvetica, sans-serif;">swift infer the type of variable from its value. So as soon as you assign any variable a number, its become Int.</u><span style="font-family: Arial, Helvetica, sans-serif;"> If you assign string its become string, and so on...</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;"><u>Swift is a type safe language, that means you can't assign a int value to a String variable.</u> So once type is infer you can't change the type of variable by assigning another type of value. If you will do so, It will be reported as compile time error.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><span style="font-family: Arial, Helvetica, sans-serif;">As you know Swift infer the type itself but you can also give the desire type to a variable or constant at time of declaration, this is known as Type Annotation. For example lets create one Double and String variable. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #008400}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; min-height: 16.0px}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo}
span.s1 {color: #bb2ca2}
span.s2 {color: #000000}
span.s3 {color: #703daa}
span.s4 {color: #272ad8}
span.s5 {color: #d12f1b}
</style>
<br />
<div class="p1">
<span class="s1"> var</span><span class="s2"> price: </span><span class="s3">Double</span><span class="s2"> = </span><span class="s4">13.0</span><span class="s2"> </span>//Swift infer floating number to Double by default</div>
<div class="p1">
<br /></div>
<div class="p3">
<span class="s1"> var</span> helloMessage: <span class="s3">String</span> = <span class="s5">"Hello reader"</span></div>
<div class="p3">
<span class="s5"><br /></span></div>
</div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">The colon(:) in declaration means </span><span style="font-family: Courier New, Courier, monospace;"><i><u>of type</u></i></span><span style="font-family: Arial, Helvetica, sans-serif;"> so that above declaration can be read as: </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"> Declare a variable called </span>price<span style="font-family: Arial, Helvetica, sans-serif;"> that is of type </span>Double<span style="font-family: Arial, Helvetica, sans-serif;">.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"> </span><span style="font-family: Arial, Helvetica, sans-serif;">Declare a variable called </span>helloMessage<span style="font-family: Arial, Helvetica, sans-serif;"> that is of type </span>String<span style="font-family: Arial, Helvetica, sans-serif;">.</span><br />
<h3>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="color: #b45f06; font-size: large;">Semicolons</span></span></h3>
<span style="font-family: Arial, Helvetica, sans-serif;"> “Unlike many other languages, Swift does not require you to write a semicolon (;) after each statement in your code, although you can do so if you wish.”</span><br />
<h3>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="color: #b45f06; font-size: large;">Data types in Swift</span></span></h3>
<div style="text-align: left;">
<ul style="text-align: left;"><span id="inlinecode" style="background-color: white; box-sizing: border-box;">
<li style="color: blue; font-size: 16px; line-height: 24px;"><span id="inlinecode" style="box-sizing: border-box; font-family: Arial, Helvetica, sans-serif; font-weight: 700;">Int</span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif;"><span style="font-weight: 700;"> </span></span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif;">Its used for whole numbers. Ex: </span><span style="color: #141412; font-family: Courier New, Courier, monospace;">var num: Int = 32</span></li>
<li style="color: blue; font-size: 16px; line-height: 24px;"><span id="inlinecode" style="box-sizing: border-box; font-family: Arial, Helvetica, sans-serif; font-weight: 700;">Float</span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif; font-weight: 700;"> </span><span style="color: #141412;"><span style="font-family: Arial, Helvetica, sans-serif;">Its used for numbers with decimal points. Ex: </span><span style="font-family: Courier New, Courier, monospace;">v</span></span><span style="color: #141412;"><span style="font-family: Courier New, Courier, monospace;">ar fNum: Float = 32.1</span></span></li>
<li style="color: blue; font-size: 16px; line-height: 24px;"><span id="inlinecode" style="box-sizing: border-box; font-family: Arial, Helvetica, sans-serif; font-weight: 700;">Double</span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif; font-weight: 700;"> </span><span style="color: #141412;"><span style="font-family: Arial, Helvetica, sans-serif;">Its used for bigger numbers with decimal points. Ex: </span><span style="font-family: Courier New, Courier, monospace;">var dNum = 32.6374</span></span></li>
<li><span id="inlinecode" style="box-sizing: border-box; color: blue; font-family: Arial, Helvetica, sans-serif; font-size: 16px; font-weight: 700; line-height: 24px;">String</span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif; font-size: 16px; font-weight: 700; line-height: 24px;"> </span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif; font-size: 16px; line-height: 24px;">Its used for ordered sequences of characters. Ex: </span><span style="font-family: Courier New, Courier, monospace;"><span style="color: #141412; font-size: 16px; line-height: 24px;">var pi = "</span><span style="color: #141412;"><span style="line-height: 24px;">π", <br /> var name: String = "you name"</span></span></span></li>
<li style="color: blue; font-size: 16px; line-height: 24px;"><span id="inlinecode" style="box-sizing: border-box; font-family: Arial, Helvetica, sans-serif; font-weight: 700;">Bool</span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif; font-weight: 700;"> </span><span style="color: #141412;"><span style="font-family: Arial, Helvetica, sans-serif;">Its used for true or false. Ex: </span><span style="font-family: Courier New, Courier, monospace;">var isRead: Bool = false</span></span></li>
<li><span id="inlinecode" style="box-sizing: border-box; color: blue; font-family: Arial, Helvetica, sans-serif; font-size: 16px; font-weight: 700; line-height: 24px;">Array</span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif; font-size: 16px; line-height: 24px;"> </span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif; font-size: 16px; line-height: 24px;">Its used for collection of same type data. Ex:</span><span style="font-family: Courier New, Courier, monospace;"><span style="color: #141412; font-size: 16px; line-height: 24px;"> </span><span style="color: #141412;"><span style="line-height: 24px;">let array = String[]()</span></span></span></li>
<li><span id="inlinecode" style="box-sizing: border-box; color: blue; font-family: Arial, Helvetica, sans-serif; font-size: 16px; font-weight: 700; line-height: 24px;">Dictionary</span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif; font-size: 16px; line-height: 24px;"> </span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif; font-size: 16px; line-height: 24px;">Its used for collection of same type data and key. </span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif; font-size: 16px; line-height: 24px;"> Ex: </span><span style="color: #141412; line-height: 24px;"><span style="font-family: Courier New, Courier, monospace;">let emptyDictionary = Dictionary<String, Float>()</span></span></li>
<li><span style="color: #141412; line-height: 24px;"><span style="font-family: Courier New, Courier, monospace;"><span id="inlinecode" style="box-sizing: border-box; color: blue; font-family: Arial, Helvetica, sans-serif; font-size: 16px; font-weight: 700;">Tuple</span></span></span><span style="color: #141412; font-family: Arial, Helvetica, sans-serif; font-size: 16px; line-height: 24px;"> Its used for collection of objects of any type. Use () to create tuple.<br /> </span><span style="color: #141412; font-size: 16px; line-height: 24px;"><span style="font-family: Courier New, Courier, monospace;">Ex: var HTTP404Error = (404, "Not Found")</span></span></li>
</span></ul>
</div>
<div>
<h3>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="color: #b45f06; font-size: large;">Tuples</span></span></h3>
</div>
<div>
<span style="font-family: Arial, Helvetica, sans-serif;"> Tuples group multiple values into a single compound value. The values in tuples an be of any types and don't have to be of the same type. This is the primary difference between Array and Tuples.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></div>
<div style="border-color: green; border-style: groove; border-width: 4px;">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #008400}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; min-height: 16.0px}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo}
p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #d12f1b}
span.s1 {color: #bb2ca2}
span.s2 {color: #000000}
span.s3 {color: #272ad8}
span.s4 {color: #d12f1b}
span.s5 {color: #4f8187}
span.s6 {color: #3d1d81}
</style>
<br />
<div class="p1">
// 1. Creating tuple</div>
<div class="p1">
<span class="s1"> let</span><span class="s2"> http404Error = (</span><span class="s3">404</span><span class="s2">, </span><span class="s4">"Not Found"</span><span class="s2">) </span>//type is (Int, String), and equals (404, "Not Found")”</div>
<div class="p2">
<br /></div>
<div class="p1">
// 2. Accessing elements of tuple</div>
<div class="p3">
<span class="s1"> let</span> (statusCode, statusMessage) = <span class="s5">http404Error</span></div>
<div class="p1">
<span class="s6"> println</span><span class="s2">(</span><span class="s4">"The status code is </span><span class="s2">\(</span><span class="s5">statusCode</span><span class="s2">)</span><span class="s4">"</span><span class="s2">) </span>//String interpolation: use \() to insert any value in string</div>
<div class="p4">
<span class="s6"> println</span><span class="s2">(</span>"The status message is <span class="s2">\(</span><span class="s5">statusMessage</span><span class="s2">)</span>"<span class="s2">)</span></div>
<div class="p2">
<br /></div>
<div class="p1">
// 3. Ignoring any element in tuple, Use underscore "_" to ignore any value</div>
<div class="p3">
<span class="s1"> let</span> (justTheStatusCode, <span class="s1">_</span>) = <span class="s5">http404Error</span></div>
<div class="p4">
<span class="s6"> println</span><span class="s2">(</span>"The status code is <span class="s2">\(</span><span class="s5">justTheStatusCode</span><span class="s2">)</span>"<span class="s2">)</span></div>
<div class="p2">
<br /></div>
<div class="p1">
//4. Accessing individual element values in tuple using index number</div>
<div class="p4">
<span class="s6"> println</span><span class="s2">(</span>"The status code is <span class="s2">\(</span><span class="s5">http404Error</span><span class="s2">.</span><span class="s3">0</span><span class="s2">)</span>"<span class="s2">)</span></div>
<div class="p4">
<span class="s6"> println</span><span class="s2">(</span>"The status message is <span class="s2">\(</span><span class="s5">http404Error</span><span class="s2">.</span><span class="s3">1</span><span class="s2">)</span>"<span class="s2">)</span></div>
<div class="p4">
<span class="s2"><br /></span></div>
<div class="p1">
// 5. Naming individual elements in a tuple when tuple defined</div>
<div class="p3">
<span class="s1"> let</span> http200Status = (statusCode: <span class="s3">200</span>, description: <span class="s4">"OK"</span>)</div>
<div class="p4">
<span class="s6"> println</span><span class="s2">(</span>"The status code is <span class="s2">\(</span><span class="s5">http200Status</span><span class="s2">.statusCode)</span>"<span class="s2">)</span></div>
<div class="p4">
<span class="s6"> println</span><span class="s2">(</span>"The status message is <span class="s2">\(</span><span class="s5">http200Status</span><span class="s2">.description)</span>"<span class="s2">)</span></div>
<div class="p4">
<span class="s2"><br /></span></div>
</div>
<div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></div>
<div>
<span style="font-family: Arial, Helvetica, sans-serif;">In above code we have created two tuples named as </span><span style="font-family: Courier New, Courier, monospace;">http404Error</span> <span style="font-family: Arial, Helvetica, sans-serif;">and</span> <span style="font-family: Courier New, Courier, monospace;">http200Status.</span><span style="font-family: Arial, Helvetica, sans-serif;">and in other parts we have used first tuple in different ways. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">1. </span><span style="font-family: Arial, Helvetica, sans-serif;">The (404, "Not Found") tuple groups together an Int and a String to give the HTTP status code two separate values: a number and a human-readable description. </span><u style="font-family: Arial, Helvetica, sans-serif;">It can be described as “a tuple of type (Int, String)”.</u><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">2. </span><span style="font-family: Arial, Helvetica, sans-serif;">We have decompose tuple in different constant named as status code and status message. We have inserted value of those constant in string using String Interpolation.</span></div>
<div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">3. </span><span style="font-family: Arial, Helvetica, sans-serif;">We have used _ to ignore second element "status message" of tuple. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">4. </span><span style="font-family: Arial, Helvetica, sans-serif;">We have use elements index number to access their value. Index start from 0.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">5. </span><span style="font-family: Arial, Helvetica, sans-serif;">We have given names to individual elements of tuple. These name helps us in accessing individual elements. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="color: red; font-family: Arial, Helvetica, sans-serif;"><u>NOTE: don't forget to see the log by opening console(opt + cmd + enter)</u></span><br />
<span style="color: red; font-family: Arial, Helvetica, sans-serif;"><u><br /></u></span>
<br />
<h3>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="color: #b45f06; font-size: large;">String Interpolation</span></span></h3>
<span style="font-family: Arial, Helvetica, sans-serif;"> </span><span style="font-family: Arial, Helvetica, sans-serif;">Its include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable. Wrap the name in parentheses and escape it with a backslash before the opening parenthesis. Ex. </span><span style="font-family: Courier New, Courier, monospace;"><span class="s1">println</span><span class="s2">(</span>"The status message is <span class="s2">\(</span><span class="s3">statusMessage</span><span class="s2">)</span>"<span class="s2">)</span></span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="s2"><br /></span></span></div>
<div>
<h3>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="color: #b45f06; font-size: large;">Optionals</span></span></h3>
</div>
<div>
<span style="font-family: Arial, Helvetica, sans-serif;"> Optionals variable either contains a value or does not contain any value at all. For example lets say you have a string value and you are trying to convert it to number/ Int. It not possible that every string can be converted into an integer. Thats why swift </span><span style="font-family: Courier New, Courier, monospace;">toInt</span><span style="font-family: Arial, Helvetica, sans-serif;"> method of </span><span style="font-family: Courier New, Courier, monospace;">String</span><span style="font-family: Arial, Helvetica, sans-serif;"> class return an optional value. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></div>
<div style="border-color: green; border-style: groove; border-width: 4px;">
<div class="p1">
<span class="s1"> let</span> possibleNumber = <span class="s2">"123"</span></div>
<div class="p1">
<span class="s1"> let</span> convertedNumber = <span class="s3">possibleNumber</span>.<span class="s4">toInt</span>()</div>
<div class="p1">
<br /></div>
</div>
<div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></div>
<div>
<span style="font-family: Arial, Helvetica, sans-serif;">Because the </span><span style="font-family: Courier New, Courier, monospace;">toInt</span><span style="font-family: Arial, Helvetica, sans-serif;"> method might fail, it returns an </span><span style="font-family: Courier New, Courier, monospace;">optional</span><span style="font-family: Arial, Helvetica, sans-serif;"> </span><span style="font-family: Courier New, Courier, monospace;">Int</span><span style="font-family: Arial, Helvetica, sans-serif;">, rather than an </span><span style="font-family: Courier New, Courier, monospace;">Int</span><span style="font-family: Arial, Helvetica, sans-serif;">. An optional </span><span style="font-family: Courier New, Courier, monospace;">Int</span><span style="font-family: Arial, Helvetica, sans-serif;"> is written as </span><span style="font-family: Courier New, Courier, monospace;">Int?</span><span style="font-family: Arial, Helvetica, sans-serif;">, not </span><span style="font-family: Courier New, Courier, monospace;">Int</span><span style="font-family: Arial, Helvetica, sans-serif;">. The question mark indicates that the value it contains is optional, meaning that it might contain some </span><span style="font-family: Courier New, Courier, monospace;">Int</span><span style="font-family: Arial, Helvetica, sans-serif;"> value, or it might contain no value at all.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<u style="background-color: #f9cb9c;"><span style="font-family: Arial, Helvetica, sans-serif;">If you will try to print or use a optional value directly then it might lead to a crash because it might be </span><span style="font-family: Courier New, Courier, monospace;">nil</span><span style="font-family: Arial, Helvetica, sans-serif;">. It means no value. Swift </span><span style="font-family: Courier New, Courier, monospace;">nil</span><span style="font-family: Arial, Helvetica, sans-serif;"> is different from Objective-C nil. In case of Objective-C its a pointer to nil but in Swift nil is not a pointer. Simply it is the absence of a value of a certain type. </span></u><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="color: red; font-family: Arial, Helvetica, sans-serif;"><u><i>Note: Optional of any type can be set to nil not only Object type.</i></u></span></div>
<div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><span style="font-family: Arial, Helvetica, sans-serif;"><b>Unwrapping Values of optionals:</b></span><span style="font-family: Arial, Helvetica, sans-serif;"> </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"> You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to true; if it has no value at all, it evaluates to false.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">Once you’re sure that the optional does contain a value, you can access its underlying value by adding an exclamation mark (!) to the end of the optional’s name. The exclamation mark effectively says, “I know that this optional definitely has a value; please use it.” This is known as forced unwrapping of the optional’s value:</span>
<br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #4f8187}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #d12f1b}
span.s1 {color: #bb2ca2}
span.s2 {color: #000000}
span.s3 {color: #3d1d81}
span.s4 {color: #d12f1b}
span.s5 {color: #4f8187}
</style>
<br />
<div class="p1">
<span class="s1"> if</span><span class="s2"> </span>convertedNumber<span class="s2"> {</span></div>
<div class="p1">
<span class="s2"> <span class="Apple-converted-space"> </span></span><span class="s3">println</span><span class="s2">(</span><span class="s4">"</span><span class="s2">\(</span>possibleNumber<span class="s2">)</span><span class="s4"> has an integer value of </span><span class="s2">\(</span>convertedNumber<span class="s2">!)</span><span class="s4">"</span><span class="s2">)</span></div>
<div class="p2">
} <span class="s1">else</span> {</div>
<div class="p3">
<span class="s2"><span class="Apple-converted-space"> </span></span> <span class="s3">println</span><span class="s2">(</span>"<span class="s2">\(</span><span class="s5">possibleNumber</span><span class="s2">)</span> could not be converted to an integer"<span class="s2">)</span></div>
<div class="p2">
}</div>
<div class="p2">
<br /></div>
</div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">If you try to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.</span><br />
<br />
<span style="font-family: Arial, Helvetica, sans-serif;">Using </span><span style="font-family: Courier New, Courier, monospace;">if else</span><span style="font-family: Arial, Helvetica, sans-serif;"> each time is boring and time consuming So swift has introduce a new concept call <b><i>Optional binding</i></b>, that we can use to Unwrap the value. <u>Optional Binding is used to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable.</u> Optional binding can be used with if and while statements to check for a value inside an optional, and to extract that value into a constant or variable, as part of a single action.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #d12f1b}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #008400}
span.s1 {color: #bb2ca2}
span.s2 {color: #4f8187}
span.s3 {color: #3d1d81}
span.s4 {color: #000000}
</style>
<br />
<div class="p1">
<span class="s1"> if</span> <span class="s1">let</span> actualNumber = <span class="s2">possibleNumber</span>.<span class="s3">toInt</span>() {</div>
<div class="p2">
<span class="s4"><span class="Apple-converted-space"> </span></span> <span class="s3">println</span><span class="s4">(</span>"<span class="s4">\(</span><span class="s2">possibleNumber</span><span class="s4">)</span> has an integer value of <span class="s4">\(actualNumber)</span>"<span class="s4">)</span></div>
<div class="p1">
} <span class="s1">else</span> {</div>
<div class="p2">
<span class="s4"><span class="Apple-converted-space"> </span></span> <span class="s3">println</span><span class="s4">(</span>"<span class="s4">\(</span><span class="s2">possibleNumber</span><span class="s4">)</span> could not be converted to an integer"<span class="s4">)</span></div>
<div class="p1">
}</div>
<div class="p3">
// prints "123 has an integer value of 123</div>
<div class="p3">
<br /></div>
</div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><span style="font-family: Arial, Helvetica, sans-serif;">It will execute else part when it is not possible to convert the given string into a number. </span>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<br />
<h3>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="color: #b45f06; font-size: large;">Operators</span></span></h3>
<span style="font-family: Arial, Helvetica, sans-serif;"> Swift supports all Objective-C operators where some of them are modified and others same as objective-C. Its also support operator overloading that we will discuss in Advance tutorial of this series. </span><br />
<br />
<span style="font-family: Arial, Helvetica, sans-serif;">All arithmetic operator are same as C except reminder operator (%). </span><u style="font-family: Arial, Helvetica, sans-serif;">Now reminder operator work with floating point and negative number</u><span style="font-family: Arial, Helvetica, sans-serif;">. Ex: </span><span class="s1">8</span><span class="s2"> % </span><span class="s1">2.5</span><span class="s2"> </span>// equals 0.5 and <span class="s1">-</span><span class="s2">9</span><span class="s1"> % </span><span class="s2">4</span><span class="s1"> </span>// equals -1<span style="font-family: Arial, Helvetica, sans-serif;"> </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"></span>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><span style="font-family: Arial, Helvetica, sans-serif;">Increment, decrement, unary minus, logical, and compound assignment operator as same as C. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">Swift supports all C based comparison operator and also introduced<u> two new comparison operator (=== and !==). </u>Which you use to test whether two object references both refer to the same object instance.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="color: orange; font-family: Arial, Helvetica, sans-serif;"><b><u>Range Operator </u></b></span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"> Swift includes two range operators, which are shortcuts for expressing a range of values:</span><br />
<br />
<ol style="text-align: left;">
<li><b><span style="font-family: Arial, Helvetica, sans-serif;">Closed Range Operator(</span><span style="font-family: Courier New, Courier, monospace;">a...b</span></b><span style="font-family: Arial, Helvetica, sans-serif;"><b>)</b><br /> The closed range operator (</span><span style="font-family: Courier New, Courier, monospace;">a...b</span><span style="font-family: Arial, Helvetica, sans-serif;">) defines a range of values that runs from </span><span style="font-family: Courier New, Courier, monospace;">a</span><span style="font-family: Arial, Helvetica, sans-serif;"> to </span><span style="font-family: Courier New, Courier, monospace;">b</span><span style="font-family: Arial, Helvetica, sans-serif;">, and include </span><span style="font-family: Courier New, Courier, monospace;">a</span><span style="font-family: Arial, Helvetica, sans-serif;"> and </span><span style="font-family: Courier New, Courier, monospace;">b</span><span style="font-family: Arial, Helvetica, sans-serif;">.</span></li>
<li><b><span style="font-family: Arial, Helvetica, sans-serif;">Half-Closed Range operator(</span><span style="font-family: Courier New, Courier, monospace;">a..<b</span></b><span style="font-family: Arial, Helvetica, sans-serif;"><b>)</b><br /> Half-closed range operator (</span><span style="font-family: Courier New, Courier, monospace;">a..<b</span><span style="font-family: Arial, Helvetica, sans-serif;">) define a range of values thats run from </span><span style="font-family: Courier New, Courier, monospace;">a</span><span style="font-family: Arial, Helvetica, sans-serif;"> to </span><span style="font-family: Courier New, Courier, monospace;">b</span><span style="font-family: Arial, Helvetica, sans-serif;"> but does not include </span><span style="font-family: Courier New, Courier, monospace;">b</span><span style="font-family: Arial, Helvetica, sans-serif;">. Thats why its called half-closed range. See the below example: </span></li>
</ol>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #008400}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; min-height: 16.0px}
span.s1 {color: #bb2ca2}
span.s2 {color: #272ad8}
span.s3 {color: #000000}
span.s4 {color: #3d1d81}
span.s5 {color: #d12f1b}
</style>
<br />
<div class="p1">
<span class="s1"> for</span> index <span class="s1">in</span> <span class="s2">1</span>...<span class="s2">5</span> {</div>
<div class="p2">
<span class="s3"> <span class="Apple-converted-space"> </span></span>//here index is of type Int. No need to write var before index</div>
<div class="p1">
<span class="Apple-converted-space"> </span> <span class="s4">println</span>(<span class="s5">"</span>\(index)<span class="s5"> times 5 is </span>\(index * <span class="s2">5</span>)<span class="s5">"</span>)</div>
<div class="p1">
}</div>
<div class="p2">
// 1 times 5 is 5</div>
<div class="p2">
// 2 times 5 is 10</div>
<div class="p2">
// 3 times 5 is 15</div>
<div class="p2">
// 4 times 5 is 20</div>
<div class="p2">
// 5 times 5 is 25</div>
<div class="p3">
<br /></div>
<div class="p2">
//If you change above range to Half-Closed(1..<5) then it will only up to 20.</div>
<div class="p2">
<br /></div>
</div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<br />
<h3>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="color: #b45f06; font-size: large;">Control Flow</span></span></h3>
<span style="font-family: Arial, Helvetica, sans-serif;"> Swift supports all control flow statement of Objective-C with a huge modification in </span><span style="font-family: Courier New, Courier, monospace;">Switch</span><span style="font-family: Arial, Helvetica, sans-serif;"> statement. Its also change the way we write conditions, Now we don't need to write brackets () around the condition you can directly write the condition followed by flower braces {}. Examples:</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #008400}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #d12f1b}
p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; min-height: 16.0px}
span.s1 {color: #bb2ca2}
span.s2 {color: #272ad8}
span.s3 {color: #4f8187}
span.s4 {color: #000000}
span.s5 {color: #3d1d81}
</style>
<br />
<div class="p1">
// If else<span class="Apple-converted-space"> </span>conditions</div>
<div class="p2">
<span class="s1"> var</span> a = <span class="s2">2</span></div>
<div class="p2">
<span class="s1"> var</span> b = <span class="s2">6</span></div>
<div class="p2">
<span class="s1"> if</span> <span class="s3">a</span> > <span class="s3">b</span> {</div>
<div class="p3">
<span class="s4"><span class="Apple-converted-space"> </span></span> <span class="s5">println</span><span class="s4">(</span>"Yes!! <span class="s4">\(</span><span class="s3">a</span><span class="s4">)</span> is not greater than <span class="s4">\(</span><span class="s3">b</span><span class="s4">)</span>"<span class="s4">)</span></div>
<div class="p2">
} <span class="s1">else</span> {</div>
<div class="p3">
<span class="s4"><span class="Apple-converted-space"> </span></span> <span class="s5">println</span><span class="s4">(</span>"No!! <span class="s4">\(</span><span class="s3">a</span><span class="s4">)</span> is greater than <span class="s4">\(</span><span class="s3">b</span><span class="s4">)</span>"<span class="s4">)</span></div>
<div class="p2">
}</div>
<div class="p4">
<br /></div>
<div class="p1">
//while loop<span class="Apple-converted-space"> </span></div>
<div class="p2">
<span class="s1"> while</span> <span class="s3">a</span> != <span class="s3">b</span> {</div>
<div class="p2">
<span class="Apple-converted-space"> </span> <span class="s3">a</span> += 2</div>
<div class="p3">
<span class="s4"> <span class="Apple-converted-space"> </span></span><span class="s5">println</span><span class="s4">(</span>"a incremented to <span class="s4">\(</span><span class="s3">a</span><span class="s4">)</span>"<span class="s4">)</span></div>
<div class="p2">
}</div>
<div class="p2">
<br /></div>
</div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><span style="color: orange; font-family: Courier New, Courier, monospace;"><b><u>Switch</u></b></span><span style="font-family: Arial, Helvetica, sans-serif;"><b><u><span style="color: orange;"> Statement</span></u></b></span><span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><span style="font-family: Arial, Helvetica, sans-serif;"> In swift </span><span style="font-family: Courier New, Courier, monospace;">switch</span><span style="font-family: Arial, Helvetica, sans-serif;"> statement has below changes </span><br />
<ul style="text-align: left;">
<li style="font-family: Arial, Helvetica, sans-serif;">No need to write break statement. Swift is smart enough to break out of matched case.</li>
<li style="font-family: Arial, Helvetica, sans-serif;">Body of each case must contain at least one executable statement. to ignore any case use break statement.</li>
<li style="font-family: Arial, Helvetica, sans-serif;">Multiple matching can be separated by comma. Ex: case 2,3,4: .</li>
<li style="font-family: Arial, Helvetica, sans-serif;">Switch value can be matched against any built in type: Int, Double, String, Tuple, Range.</li>
<li><span style="font-family: Arial, Helvetica, sans-serif;">switch statement must be </span><i style="font-family: Arial, Helvetica, sans-serif;">exhaustive</i><span style="font-family: Arial, Helvetica, sans-serif;">. Using </span><span style="font-family: Courier New, Courier, monospace;">default</span><span style="font-family: Arial, Helvetica, sans-serif;"> case is easy way to get rid of this condition. </span></li>
</ul>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #008400}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #d12f1b}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo}
p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #bb2ca2}
p.p5 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #4f8187}
p.p6 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #272ad8}
span.s1 {color: #bb2ca2}
span.s2 {color: #000000}
span.s3 {color: #272ad8}
span.s4 {color: #703daa}
span.s5 {color: #4f8187}
span.s6 {color: #d12f1b}
span.s7 {color: #3d1d81}
</style>
<br />
<div class="p1">
<span class="s1"> let</span><span class="s2"> count = </span><span class="s3">3_000_000_000_000</span><span class="s2"> </span>//you can use _ in number to make it redable</div>
<div class="p2">
<span class="s1"> let</span><span class="s2"> countedThings = </span>"stars in the Milky Way"</div>
<div class="p3">
<span class="s1"> var</span> naturalCount: <span class="s4">String</span></div>
<div class="p4">
switch<span class="s2"> </span><span class="s5">count</span><span class="s2"> {</span></div>
<div class="p4">
case<span class="s2"> </span><span class="s3">0</span><span class="s2">,</span><span class="s3">1</span><span class="s2">:</span></div>
<div class="p5">
<span class="s2"><span class="Apple-converted-space"> </span></span> naturalCount<span class="s2"> = </span><span class="s6">"very few"</span></div>
<div class="p3">
<span class="s1"> case</span> <span class="s3">2</span>...<span class="s3">3</span>:</div>
<div class="p5">
<span class="s2"><span class="Apple-converted-space"> </span></span> naturalCount<span class="s2"> = </span><span class="s6">"a few"</span></div>
<div class="p3">
<span class="s1"> case</span> <span class="s3">4</span>...<span class="s3">9</span>:</div>
<div class="p5">
<span class="s2"><span class="Apple-converted-space"> </span></span> naturalCount<span class="s2"> = </span><span class="s6">"several"</span></div>
<div class="p3">
<span class="s1"> case</span> <span class="s3">10</span>...<span class="s3">99</span>:</div>
<div class="p5">
<span class="s2"><span class="Apple-converted-space"> </span></span> naturalCount<span class="s2"> = </span><span class="s6">"tens of"</span></div>
<div class="p6">
<span class="s1"> case</span><span class="s2"> </span>100<span class="s2">...</span>999<span class="s2">:</span></div>
<div class="p2">
<span class="s2"><span class="Apple-converted-space"> </span></span> <span class="s5">naturalCount</span><span class="s2"> = </span>"hundreds of"</div>
<div class="p6">
<span class="s1"> case</span><span class="s2"> </span>1000<span class="s2">...</span>999_999<span class="s2">:</span></div>
<div class="p2">
<span class="s2"><span class="Apple-converted-space"> </span></span> <span class="s5">naturalCount</span><span class="s2"> = </span>"thousands of"</div>
<div class="p4">
default<span class="s2">:</span></div>
<div class="p2">
<span class="s2"><span class="Apple-converted-space"> </span></span> <span class="s5">naturalCount</span><span class="s2"> = </span>"millions and millions of"</div>
<div class="p3">
}</div>
<div class="p5">
<span class="s7"> println</span><span class="s2">(</span><span class="s6">"There are </span><span class="s2">\(</span>naturalCount<span class="s2">)</span><span class="s6"> </span><span class="s2">\(</span>countedThings<span class="s2">)</span><span class="s6">."</span><span class="s2">)</span></div>
<div class="p1">
// prints "There are millions and millions of stars in the Milky Way.</div>
<div class="p1">
<br /></div>
</div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><span style="font-family: Arial, Helvetica, sans-serif;">In above example we are matching a number and commenting about number of stars. In case first we are trying to match multiple values against some value to switch. In rest of conditions we we are trying to match switch value against range of value. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;">Without the default statement this switch will not become</span><i style="font-family: Arial, Helvetica, sans-serif;"> exhaustive</i><span style="font-family: Arial, Helvetica, sans-serif;"> because its not matching all possible value of count. Thats means </span><span style="font-family: Arial, Helvetica, sans-serif;">every possible value of the type being considered must be matched by one of the switch case.</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;"><b><u><span style="color: #bf9000;">Switch and Tuple:</span></u></b> We can also use tuple to test multiple value in switch statement. You can also bind the elements of tuple to variable or constant. See below example:</span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo}
p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; min-height: 16.0px}
p.p3 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #4f8187}
p.p4 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo; color: #d12f1b}
span.s1 {color: #bb2ca2}
span.s2 {color: #272ad8}
span.s3 {color: #703daa}
span.s4 {color: #000000}
span.s5 {color: #4f8187}
span.s6 {color: #d12f1b}
</style>
<br />
<div class="p1">
<span class="s1"> let</span> somePoint = (<span class="s2">1</span>, <span class="s2">1</span>)</div>
<div class="p1">
<span class="s1"> var</span> comment:<span class="s3">String</span></div>
<div class="p2">
<br /></div>
<div class="p3">
<span class="s1"> switch</span><span class="s4"> </span>somePoint<span class="s4"> {</span></div>
<div class="p1">
<span class="s1"> case</span> (<span class="s2">0</span>, <span class="s2">0</span>):</div>
<div class="p4">
<span class="s4"><span class="Apple-converted-space"> </span></span> <span class="s5">comment</span><span class="s4"> = (</span>"(0, 0) is at the origin"<span class="s4">)</span></div>
<div class="p1">
<span class="s1"> case</span> (<span class="s1">_</span>, <span class="s2">0</span>):</div>
<div class="p4">
<span class="s4"><span class="Apple-converted-space"> </span></span> <span class="s5">comment</span><span class="s4"> = (</span>"(<span class="s4">\(</span><span class="s5">somePoint</span><span class="s4">.</span><span class="s2">0</span><span class="s4">)</span>, 0) is on the x-axis"<span class="s4">)</span></div>
<div class="p1">
<span class="s1"> case</span> (<span class="s2">0</span>, <span class="s1">_</span>):</div>
<div class="p4">
<span class="s4"><span class="Apple-converted-space"> </span></span> <span class="s5">comment</span><span class="s4"> = (</span>"(0, <span class="s4">\(</span><span class="s5">somePoint</span><span class="s4">.</span><span class="s2">1</span><span class="s4">)</span>) is on the y-axis"<span class="s4">)</span></div>
<div class="p1">
<span class="s1"> case</span> (-<span class="s2">2</span>...<span class="s2">2</span>, -<span class="s2">2</span>...<span class="s2">2</span>):</div>
<div class="p3">
<span class="s4"><span class="Apple-converted-space"> </span></span> comment<span class="s4"> = (</span><span class="s6">"(</span><span class="s4">\(</span>somePoint<span class="s4">.</span><span class="s2">0</span><span class="s4">)</span><span class="s6">, </span><span class="s4">\(</span>somePoint<span class="s4">.</span><span class="s2">1</span><span class="s4">)</span><span class="s6">) is inside the box"</span><span class="s4">)</span></div>
<div class="p1">
<span class="s1"> case</span> (<span class="s1">let</span> x, <span class="s1">let</span> y):</div>
<div class="p4">
<span class="s4"> <span class="Apple-converted-space"> </span>(</span>"(<span class="s4">\(x</span><span class="s4">)</span>, <span class="s4">\(y</span><span class="s4">)</span>) is outside of the box"<span class="s4">)</span></div>
<div class="p1">
}</div>
<div class="p1">
<br /></div>
</div>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><span style="font-family: Arial, Helvetica, sans-serif;">Above code will print "(1, 1) is inside the box" and in above switch statement we have not used default statement, because without that our switch statement is . If you wish to use default you can replace case (let x, let y) by default statement and replace x and y with indexes of individual elements. </span><br />
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span><span style="font-family: Arial, Helvetica, sans-serif;">Thats it, in basic. In next part we will discuss Collections, Functions, Class, Closures etc.</span><br />
<span style="background-color: #fefdfa; color: #333333; font-size: 16px; line-height: 22.399999618530273px;"><span style="font-family: Arial, Helvetica, sans-serif;">Thanks for reading!! Please do not forget to leave your valuable comments. Bye Bye !!</span></span><span style="font-family: Arial, Helvetica, sans-serif;"><br /></span>
<span style="font-family: Arial, Helvetica, sans-serif;"><br /></span></div>
</div>
Anonymoushttp://www.blogger.com/profile/03540465319086699554noreply@blogger.com0tag:blogger.com,1999:blog-6912106156720688131.post-12564041935544400522013-02-24T07:23:00.000-08:002014-06-29T11:43:47.705-07:00Introduction to Modern Objective C<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
<span class="GingerNoCheckStart"></span>Hello friends!! In this post I am going to talk about Modern Objective C. It comes with Xcode 4.5 and it is a feature of LLVM Copiler 4.0 so if you don't have Xcode 4.5, then <u>please update your Xcode to latest version.</u> This tutorial assume that you have prior knowledge of Objective C, if you don't know Objective C then you can start here <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html" target="_blank">Objective-C Programming Guide</a>.</div>
<br />
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Modern Objective C does not introduce any new construct but it simplify the common Objective C programming pattern, makes program more concise and avoids making common mistakes. More frankly it improve the safety of container creation. </span></div>
<br />
<div style="text-align: justify;">
<span style="font-family: Times, Times New Roman, serif;">Now lets start with some coding and see all the feature introduce in Modern Objective C. First create a project using xcode and name it as <u>"ModernOBJCTest"</u>.</span></div>
<br />
<div style="text-align: justify;">
1. File --> New Project --> Single View Application --> On Screen Instruction</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCK4Evh4q3iRXVJRFu5LqRUdv29oXuJkphzdR7rI6bFb9nJQS4-HgUavLeVt74orDn3Y1kIoLXM1e1irEfm6G3hgLqGn4GIsJToyuGhw5SDlkzQB21dh7bGEbGb0ggArJviZKdPj47Ny4/s1600/Screen+Shot+2012-12-06+at+7.56.11+AM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCK4Evh4q3iRXVJRFu5LqRUdv29oXuJkphzdR7rI6bFb9nJQS4-HgUavLeVt74orDn3Y1kIoLXM1e1irEfm6G3hgLqGn4GIsJToyuGhw5SDlkzQB21dh7bGEbGb0ggArJviZKdPj47Ny4/s400/Screen+Shot+2012-12-06+at+7.56.11+AM.png" height="266" width="400" /></a></div>
<h4 style="text-align: left;">
</h4>
<h4>
<u style="color: #b45f06;"><br /></u></h4>
<h4>
<u style="color: #b45f06;">Property Synthesis</u></h4>
<div style="text-align: justify;">
<span style="font-weight: normal;"><br /></span>
<span style="font-weight: normal;"> In Modern Objective - C you do not need to </span>synthesize <span style="font-weight: normal;">the properties, xcode will do it for you. So now you can say bye, bye to "</span><i>@synthesize"</i><span style="font-weight: normal;"> keyword.</span><br />
<span style="font-weight: normal;"></span><br />
<ul>
<li><span style="font-weight: normal;">Name of instance variable in default synthesis will be underscore ('_') prefixed </span></li>
<li><span style="font-weight: normal;">You need to define the name of instance variable if you are defining custom accessor and setter</span></li>
</ul>
</div>
<h4 style="text-align: justify;">
<u style="color: #b45f06;">Private Methods</u></h4>
<span style="font-weight: normal;"><br /></span>
<span style="font-weight: normal;"> Till now what are you doing for private methods? Have you defined it in interface file(.h file) Yes!! no no... its not a good idea, sorry but please read the basic of OOPs, if No, you are a good programmer and i think you have defined it in category YES!! its cool but now forget it too, because you can write your private methods in implementation file (.m file) without declaring it in interface file or in a category. Thanks to xcode you don't have to worry about order of methods because at time of compilation xcode buffers the body of methods and looks for signatures. For example check the codes under </span>number literals<span style="font-weight: normal;">.</span>
<br />
<h4 style="text-align: left;">
<u style="color: #b45f06;">NSNumber Literals</u></h4>
<div>
<u style="color: #b45f06;"><br /></u></div>
<div>
<div style="text-align: left;">
<span style="text-align: justify;"><span style="color: #b45f06;"> </span>We use NSNumber class to wrap scaler(signed and unsigned short, char, int, long, long long, float, double, BOOL) values in Objective C Object. All scaler values also known as </span><i style="text-align: justify; text-decoration: underline;">boxed values.</i></div>
</div>
<div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Lest go-ahead and create a method in <i><span style="color: blue;">"MOBJCViewController.m"</span></i> as follows - </div>
<div style="text-align: justify;">
<br /></div>
</div>
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self numberLiteral];
}
- (void)numberLiteral {
NSNumber *n1 =@41; // equivalent to [NSNumber numberWithInteger:41];
NSLog(@"Integer number = %i",[n1 integerValue]);
NSNumber *n2 = @34.234; // equivalent to [NSNumber numberWithFloat:34.234];
NSLog(@"Float number = %.2f",[n2 floatValue]);
NSNumber *n3 = @31U; // equivalent to [NSNumber numberWithUnsignedInt:31U];
NSLog(@"Unsigned Int = %u",[n3 unsignedIntegerValue]);
NSNumber *n4 = @3456688876LL;//equivalent to [NSNumber numberWithLongLong:3456688876];
NSLog(@"Long Long Value = %lld",[n4 longLongValue]);
}
</pre>
</div>
<div>
<br />
<div style="text-align: justify;">
<div style="text-align: left;">
Now hit the run command and see the log in Xcode debug area -
<br />
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<div style="background-color: yellow; border-bottom-color: green; border-bottom-style: solid; border-bottom-width: 1px; text-align: center;">
LOG (Shift + Command + Y)</div>
Integer number = 41 <br />
Float number = 34.23 <br />
Unsigned Int = 31 <br />
Long Long Value = 3456688876</div>
</div>
<div style="text-align: left;">
<span style="text-decoration: underline;"><span style="color: orange;"><br /></span></span></div>
In Modern Objective C any bool, char, numeric literal prefixed with '@' character will be evaluated to a pointer to an NSNumber object initialized with that value. Compiler will automatically take care of type of variable.<br />
<br />
<h4 style="text-align: left;">
<span style="color: #b45f06;"><u>BOOL Literals</u></span></h4>
<div>
<span style="color: #b45f06;"><u><br /></u></span></div>
<div>
<span style="color: #b45f06;"> </span> Similar to number literals you don't need to use NSNumber class methods to convert BOOL values in number, just put '@' before YES and NO. Lets check in code, now create boolLiterals methods and call it from viewWillAppear: method as follows -</div>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">- (void)boolLiterals {
NSNumber *numberYes = @YES;
NSLog(@"value of numberYes = %d",[numberYes boolValue]);//1 means YES and Zero means NO
}
</pre>
</div>
<br />
Check Xcode console, you will find 1 as value of 'numberYes'. Similarly you can create a number literal by assigning any character <i>NSNumber *c = @'c';.</i><br />
<i><b><span style="color: red;">Note: NSNumber literals only support literal scalar values after the '@' that means you can write @41, @YES, @'c' but not @INT_MIN because compiler translate your code as NSNumber *n1 = [NSNumber numberWithInteger: 41] and so-on .</span></b></i></div>
</div>
<div>
<h4>
<span style="color: #b45f06;"><u><br /></u></span></h4>
<h4>
<span style="color: #b45f06;"><u>Array Literals</u></span></h4>
</div>
<div>
<span style="color: #b45f06;"><u><br /></u></span></div>
<div>
<div style="text-align: justify;">
Array literals enable you to create NSArray in very less amount of code. No need to use the class methods to create the array. Array created using literal are immutable(you can not add or remove items from resulting array). Lets write code to create an array of friend and say hello to all.</div>
</div>
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">- (void)sayHelloToFriends:(NSArray*)friends {
for (int i = 0; i<friends.count; i++) {
NSLog(@"Hello %@!!",friends[i]);
}
}
</pre>
</div>
<br />
In modern objective c, you can acces a particular element without using <i><u>objectAtIndex:</u></i> method. If you have completed the above method then call it in <i style="text-decoration: underline;">viewWillAppear:</i> method of view controller as follows.
<br />
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//is array literals supported by compiler?
#if __has_feature(objc_array_literals)
//Cheers!! literals are supported
//create array using literals
NSArray *friends = @[ @"Joe", @"Kevin", @"Amit", @"Deepthi" ];
NSLog(@"Array is created using literal");
#else
//literals are not supported use old method
NSArray *friends = [NSArray arrayWithObjects:@"Joe", @"Kevin", @"Amit", @"Deepthi",nil];
NSLog(@"Array is created using NSArray class method");
#endif
//call sayHelloToFriends: method and pass array of friends
[self sayHelloToFriends:friends];
}
</pre>
</div>
<br />
We are checking availability of array literals by "__has_feature" check. Now RUN the application and check the output in log -<br />
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<div style="background-color: yellow; border-bottom-color: green; border-bottom-style: solid; border-bottom-width: 1px; text-align: center;">
OUTPUT </div>
Array is created using literal<br />
Hello Joe!!<br />
Hello Kevin!!<br />
Hello Amit!!<br />
Hello Deepthi!!
</div>
<br />
<b><u>HOW ITS WORK?</u></b><br />
<div style="text-align: justify;">
When you create number or array using literals then compiler generates code for you. Compiler will generate following code for above array -</div>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;"> //first holds your all items</pre>
<pre class="brush: objc; toolbar: false;gutter: false;"> id objects[] = {@"Joe", @"Kevin", @"Amit", @"Deepthi"};</pre>
<pre class="brush: objc; toolbar: false;gutter: false;"> //calculate number of items
NSUInteger count = sizeof(objects)/ sizeof(id);</pre>
<pre class="brush: objc; toolbar: false;gutter: false;"> //create array using class method
friends = [NSArray arrayWithObjects:objects count:count];</pre>
</div>
<h4>
<u style="color: #b45f06;"><br />Dictionary Literals</u></h4>
<div>
<u style="color: #b45f06;"><br /></u></div>
<div>
<div style="text-align: justify;">
Personally I love dictionary literals because it simplifies the the process of creating a dictionary and code is easy to understand and read. Lets create a dictionary using literals-<br />
<br /></div>
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//create a dictionary @{key:object, key:object}
NSDictionary *person = @{
@"name" : @"Mithilesh Kumar",
@"age" : @22,
@"email" : @"talkmithilesh123@gmail.com",
};
[self printDictionary:person];
}
- (void)printDictionary:(NSDictionary*)dictionary {
// Person details
NSLog(@"NAME : %@",[dictionary objectForKey:@"name"]);
NSLog(@"AGE : %d",[dictionary[@"age"] integerValue]);
NSLog(@"EMAIL : %@",[dictionary objectForKey:@"email"]);
}
</pre>
</div>
<br />
<div style="text-align: justify;">
Have you notice the new way to access object from dictionary <u><i>[dictionary[@"age"] integerValue]</i></u> Yes!! you can access the object without using instance method <i><u>objectForKey:</u></i> .<br />
<br /></div>
<div style="text-align: justify;">
<span style="color: #cc0000;">NOTES: All container created using literals are immutable and you can not create constant using literals <u><i>static NSArray *arr = @[];</i></u> compiler will generates error. If you want to create constant using literals, use <u style="font-style: italic;">+(<span class="s1">void</span>)initialize</u> class method.</span></div>
<br />
<h4>
<span style="color: #b45f06;"><u>Object Subscripting</u></span></h4>
<br />
<div style="text-align: justify;">
Any Objective - C object can be used with subscript ( [ ] ) operator. By default objective C compiler support subscripting for NSArray and NSDictionary for example -</div>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;"> NSMutableArray *array = [NSMutableArray arrayWithObjects:@"First",@"Second", nil];
NSUInteger idx = @2;
id newObject = @"New-Second";
id oldObject = array[idx];
array[idx] = newObject; // replace oldObject with newObject
NSArray *keys = @[@"one", @"two"];
NSArray *values = @[@"First", @"Second"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjects:values forKeys:keys];
NSString *key = @"two";
oldObject = dictionary[key];
dictionary[key] = newObject; // replace oldObject with newObject
</pre>
</div>
<br />
<br />
<div style="text-align: justify;">
You can introduce subscripting in your objects by implementing following four methods-</div>
<ol style="text-align: left;">
<li style="text-align: justify;">- (id)objectAtIndexdSubscript:(NSUInteger)idx</li>
<li style="text-align: justify;">- (void)setObject:(id)object atIndexedSubscript:(NSUInteger)idx </li>
<li style="text-align: justify;">- (id)objectForKeyedSubscript:(NSUInteger)idx</li>
<li style="text-align: justify;">- (void)setObject:(id)object forKeyedSubscript:(NSUInteger)idx</li>
</ol>
<div>
<div style="text-align: justify;">
First two (1 and 2) are used for <i><u><span style="color: red;">Array Style Subscripting</span></u></i> and last two (3 and 4) are used for <i><span style="color: red;"><u>Dictionary Style Subscripting</u></span></i>. You can implement any set of methods as your requirement. Actually when we use subscripts with array or dictionary objects then compiler translate that in above methods calls. For Example NSArray only implement <u><i>- (id)objectAtIndexdSubscript:(NSUInteger)idx</i></u>. Lets write a simple SongList class to see the Array Style subscripting - </div>
</div>
<div>
<br />
<b>Add a class (Subclass of NSObject) and replace the code by following code</b><br />
<br /></div>
<div>
<u><b>SongList.h</b></u><br />
<u><b><br /></b></u></div>
<div>
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">#import < Foundation/Foundation.h >
#import "Song.h"
@interface SongList : NSObject {
NSMutableArray *list;
}
- (Song*)objectAtIndexedSubscript:(NSUInteger)idx;
- (void)setObject:(Song*)song atIndexedSubscript:(NSUInteger)idx;
@end
</pre>
</div>
</div>
<div>
<u><b><br /></b></u>
<u><b>SongList.m</b></u>
<br />
<u><b><br /></b></u></div>
<div>
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">#import "SongList.h"
@implementation SongList
- (id)init
{
self = [super init];
if (self) {
list = [[NSMutableArray alloc] init];
}
return self;
}
- (Song*)objectAtIndexedSubscript:(NSUInteger)idx {
return ((Song*)list[idx]);
}
- (void)setObject:(Song*)song atIndexedSubscript:(NSUInteger)idx {
list[idx] = song;
}
@end
</pre>
</div>
<br />
<div style="text-align: justify;">
To test the above code first create a <i>"Song"</i> class with a property called <i>"name"</i> and then import both these classes in <b><u><i>viewController</i></u></b> class and then replace the <u><i>viewDidLoad:</i></u> method and check the log -</div>
<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">- (void)viewDidLoad
{
[super viewDidLoad];
SongList *sList = [[SongList alloc] init];
Song *s1 = [[Song alloc] init];
s1.name = @"song - 1 ";
sList[0] = s1;
NSLog(@"Song Name is %@",sList[0].name);
}
</pre>
</div>
<br />
<br />
<h4>
<span style="color: #b45f06;"><u>Migrating To Modern Objective - C</u></span></h4>
<br />
<div style="text-align: justify;">
You can migrate your old projects to Modern Objective - C syntax by using Xcode refactor tool as follows -</div>
<ol style="text-align: left;">
<li style="text-align: justify;">Go to Edit menu</li>
<li style="text-align: justify;">Go to Refactor </li>
<li style="text-align: justify;">Click on Convert to Modern Objective - C Syntax...</li>
<li style="text-align: justify;">Follow on screen instructions</li>
</ol>
<div>
<div style="text-align: justify;">
Hey Cheers!! now you have completed almost every thing related to Modern Objective C. Following table lists all required tools and backward compatibility of Modern Objective C's features - </div>
</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhYRnx8dQsam6P9lnKsH8oiIaxFruCU-hvbIeyZXWwAAbgfxVtFgd4Esf-H03uZ3marE7rBVrhCg7Llvlwr5t9fOin7lu1O5EpZMicNvpULqGucTRwrcBDxPhNvFWe88W57e0XN7mHPKX0/s1600/Screen+Shot+2013-02-24+at+6.21.41+PM.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img alt="compatibility list " border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhYRnx8dQsam6P9lnKsH8oiIaxFruCU-hvbIeyZXWwAAbgfxVtFgd4Esf-H03uZ3marE7rBVrhCg7Llvlwr5t9fOin7lu1O5EpZMicNvpULqGucTRwrcBDxPhNvFWe88W57e0XN7mHPKX0/s640/Screen+Shot+2013-02-24+at+6.21.41+PM.png" height="316" title="compatibility list " width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
You can check updated list <a href="https://developer.apple.com/library/ios/#releasenotes/ObjectiveC/ObjCAvailabilityIndex/index.html" target="_blank">here</a>. </div>
<div class="separator" style="clear: both; text-align: left;">
Hey Guys Thanks for reading!! Please don not forget to leave your valuable comments. Bye Bye !!</div>
</div>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/03540465319086699554noreply@blogger.com3tag:blogger.com,1999:blog-6912106156720688131.post-45795998458616453262012-10-13T14:46:00.002-07:002012-10-13T15:04:51.566-07:00integrating facebook and twitter in iOS 6 Apps (Social Framework)<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Hello friends!! In this post, i am going to talk about social framework(introduce in iOS6). How to integrate facebook or twitter in iOS6 App.</div>
<div style="text-align: justify;">
Social framework is introduce in iOS6 and by using it we can connect to facebook, twitter or <a href="http://weibo.com/" target="_blank">weibo.com</a>, no need of any third party SDKs. To learn social framework in iOS6 you should have <span style="color: red;">Xcode 4.5</span>. Lets start without wasting time first create a single view application and design your first screen as following screen -</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgolhNElpESPQtnOtzG9oamJVasGqEJS5X6-Iotuq-thjwTebScljpwwo8VC68Vkjgu4BCqbZB6wyXvq1L1RKhlp-mJhCVuVEaBTEdiMdp0tnb6AWfGVtrJdboNS2peI9dSuCpIsWhle34/s1600/Screen+Shot+2012-10-13+at+11.33.25+PM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgolhNElpESPQtnOtzG9oamJVasGqEJS5X6-Iotuq-thjwTebScljpwwo8VC68Vkjgu4BCqbZB6wyXvq1L1RKhlp-mJhCVuVEaBTEdiMdp0tnb6AWfGVtrJdboNS2peI9dSuCpIsWhle34/s320/Screen+Shot+2012-10-13+at+11.33.25+PM.png" width="214" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Now add Social framework to your project - </div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<ol style="text-align: left;">
<li>Click on project name in project navigator</li>
<li>Select the project under target in middle pan of Xcode</li>
<li>Make sure that "Build Phases" tab is selected</li>
<li>Expand the "Link binary with libraries", click on triangle</li>
<li>Click on add item(+ button) in left corner of this section </li>
<li>Search social in search bar (comes after clicking on + button)</li>
<li>Select the "Social.framework" framework and click on "Add" button </li>
</ol>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-T-FIIwEdIBPXRstkranVvS52hckRtbfsUrMHHpRz5gMyaWthaBmu7r731Sk0ciqdhWJHebKPeIdbhdTDgndVpdLNzg_ImPLRXKj74Kpj7etnJpXJ1lBI-7A8IT-qKzutbQtDtdCiO7U/s1600/Screen+Shot+2012-10-13+at+11.54.51+PM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="231" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-T-FIIwEdIBPXRstkranVvS52hckRtbfsUrMHHpRz5gMyaWthaBmu7r731Sk0ciqdhWJHebKPeIdbhdTDgndVpdLNzg_ImPLRXKj74Kpj7etnJpXJ1lBI-7A8IT-qKzutbQtDtdCiO7U/s400/Screen+Shot+2012-10-13+at+11.54.51+PM.png" width="400" /></a></div>
<div>
<br /></div>
<div>
Cheers you have completed the first step of this tutorial. Now import the social framework header file "Social.h" in ViewController.h file of your project.<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">// import social header file
#import<Social/Social.h>
</pre>
</div>
<br />
Add following two methods to "ViewController.h" file and connect them to respective button's touch event in respective view controller.<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;"> //called on tap of facebook button
- (IBAction)postOnFacebookButtonTapped:(id)sender;
//called on tap of tweet button
- (IBAction)tweetButtonTapped:(id)sender;
</pre>
</div>
<br />
Similarly add body of these two methods in "ViewController.m" file<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">- (IBAction)postOnFacebookButtonTapped:(id)sender {
}
- (IBAction)tweetButtonTapped:(id)sender {
}
</pre>
</div>
<br />
<div style="text-align: justify;">
We have added the required framework and methods to our project now it is the time to write the actual code. Social framework provides built in composer (<span style="background-color: white; font-family: Courier, Consolas, monospace; font-size: 14px;">SLComposeViewController</span>), which we can pressent to user with pre loaded text, URL, and images so that user can tweet or post on their timeline. To present the composer we need to create an instance of this class. <u>We can not edit or add any thing to the composer without informing the user. So we must add any initial content before presenting the composer to the user.</u> After presenting the composer, only user can edit the content. </div>
<div style="text-align: justify;">
</div>
<div style="text-align: justify;">
<span style="background-color: white; font-family: Courier, Consolas, monospace; font-size: 14px; text-align: left;">+(SLComposeViewController*)composeViewControllerForServiceType:(</span><a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/c_ref/NSString" style="background-color: white; color: #003366; font-family: Courier, Consolas, monospace; font-size: 14px; text-align: left; text-decoration: none;">NSStrin</a>g<span style="background-color: white; font-family: Courier, Consolas, monospace; font-size: 14px; text-align: left;">*) </span><em style="background-color: white; font-family: 'Lucida Grande', Geneva, Helvetica, Arial, sans-serif; font-size: 14px; text-align: left;">serviceType </em></div>
<div style="text-align: justify;">
<em style="background-color: white; font-family: 'Lucida Grande', Geneva, Helvetica, Arial, sans-serif; font-size: 14px; text-align: left;"><br /></em></div>
<div style="text-align: left;">
<span style="font-family: Lucida Grande, Geneva, Helvetica, Arial, sans-serif;"><span style="font-size: 14px;">Above method is use to create the instance of </span></span><span style="background-color: white; font-family: Courier, Consolas, monospace; font-size: 14px;">SLComposeViewController</span><span style="font-family: Lucida Grande, Geneva, Helvetica, Arial, sans-serif;"><span style="font-size: 14px;"> and for it we need to pass service type. Service type tells the targeted social website like facebook, twitter and weibo. Service types are as follows -</span></span></div>
<div class="p1">
</div>
<ul style="text-align: left;">
<li><span style="color: #38761d;">SLServiceTypeTwitter</span></li>
<li><span style="color: #38761d;">SLServiceTypeFacebook</span></li>
<li><span style="color: #38761d;">SLServiceTypeSinaWeibo<span style="font-family: 'Lucida Grande', Geneva, Helvetica, Arial, sans-serif; font-size: 14px;"> </span></span></li>
</ul>
<div>
<span style="font-family: Lucida Grande, Geneva, Helvetica, Arial, sans-serif;"><span style="font-size: 14px;">You should pass desire service type to create the respective composer. Before creating or presenting the composer we should check the availability of service type or reachability of site. For this we can use following class method - </span></span></div>
<div>
<span style="font-family: Lucida Grande, Geneva, Helvetica, Arial, sans-serif;"><span style="font-size: 14px;"><br /></span></span></div>
<div>
<span style="background-color: white; font-family: Courier, Consolas, monospace; font-size: 14px;">+ (BOOL)isAvailableForServiceType:(</span><a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/c_ref/NSString" style="background-color: white; color: #003366; font-family: Courier, Consolas, monospace; font-size: 14px; text-decoration: none;">NSString</a><span style="background-color: white; font-family: Courier, Consolas, monospace; font-size: 14px;"> *)</span><em style="background-color: white; font-family: 'Lucida Grande', Geneva, Helvetica, Arial, sans-serif; font-size: 14px;">serviceType</em></div>
<div>
<em style="background-color: white; font-family: 'Lucida Grande', Geneva, Helvetica, Arial, sans-serif; font-size: 14px;"><br /></em></div>
<div>
<span style="font-family: Lucida Grande, Geneva, Helvetica, Arial, sans-serif;"><span style="font-size: 14px;">This methods returns BOOL value where NO represents one of following - </span></span></div>
<div>
<ol style="text-align: left;">
<li><span style="font-family: 'Lucida Grande', Geneva, Helvetica, Arial, sans-serif; font-size: 14px;">User's twitter or facebook account is not set up on device</span></li>
<li><span style="font-family: 'Lucida Grande', Geneva, Helvetica, Arial, sans-serif; font-size: 14px;">Desire site is not available </span></li>
</ol>
<div>
<span style="font-family: Lucida Grande, Geneva, Helvetica, Arial, sans-serif;"><span style="font-size: 14px;">Now lets implement </span></span>postOnFacebookButtonTapped: method </div>
</div>
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">- (IBAction)postOnFacebookButtonTapped:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *fbComposer = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeFacebook];
//set the initial text message
[fbComposer setInitialText:@"Hi i am coding for bugs!!"];
//add url
if ([fbComposer addURL:[NSURL URLWithString:@"www.kmithi.blogspot.com"]]) {
NSLog(@"Blog url added");
}
// you can remove all added URLs as follows
//[fbComposer removeAllURLs];
//add image to post
if ([fbComposer addImage:[UIImage imageNamed:@"strongBinary"]]) {
NSLog(@"strong binary added to the post");
}
if ([fbComposer addImage:[UIImage imageNamed: @"scan.jpg"]]) {
NSLog(@"scan is added to the post");
}
//remove all added images
//[fbComposer removeAllImages];
//present the composer to the user
[self presentViewController:fbComposer animated:YES completion:nil];
}else {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Facebook Error"
message:@"You may not have set up facebook service on your device or\n You may not connected to internent.\nPlease check ..."
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alertView show];
}
}
</pre>
</div>
<br />
Yah!! It is this much easy any one can add facebook and twitter to their applications. All methods use to set initial text or add/ remove URLs and images returns BOOL values where YES tells that successfully added/ removed image or URL. You can add more than one image but not URL only last URL will be posted to your timeline. If your account is not set up then first set up it (Settings --> facebook) otherwise it will returns NO while checking the availability of service or error while posting. Similarly we can implement tweetButtonTapped: method-<br />
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;">- (IBAction)tweetButtonTapped:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {
SLComposeViewController *twitterComposer = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
//add initial text
[twitterComposer setInitialText:@"Tweeting from iPhone 5 #TesingApp"];
//present composer
[self presentViewController:twitterComposer animated:YES completion:nil];
} else {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"twitter Error"
message:@"You may not have set up twitter service on your device or\n You may not connected to internent.\nPlease check ..."
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alertView show];
}
}
</pre>
</div>
<br />
Composer view controllers looks like follow -<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbjILaZHKsj87qAjXWgfg7WKcgjCWXJq6XJUXo3IsrbYR8KYcnOHcJCYdjLfKtT_P8k6-KovwWsJp44oS11NZGWn4L-Z6ZhqIusAcAwD4gyH3ov1eiOcNDr14rTvN5hkT4MjQqf4w-fJk/s1600/Screen+Shot+2012-10-14+at+2.17.42+AM.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbjILaZHKsj87qAjXWgfg7WKcgjCWXJq6XJUXo3IsrbYR8KYcnOHcJCYdjLfKtT_P8k6-KovwWsJp44oS11NZGWn4L-Z6ZhqIusAcAwD4gyH3ov1eiOcNDr14rTvN5hkT4MjQqf4w-fJk/s320/Screen+Shot+2012-10-14+at+2.17.42+AM.png" width="211" /></a>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXTqjmhsgOg46wilDtnZ2xmoatVC17IuMAhlpPO9TfZ5VCRr26O1o1Fbv_2mkdKNme74OGAJMALqaGZ9aQEu2YE5a-aLvjjSHmd7GSopTX2E1zEfAkR-1_lM0YOR9BWUnE3cnjy0wujYg/s1600/Screen+Shot+2012-10-14+at+2.18.39+AM.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXTqjmhsgOg46wilDtnZ2xmoatVC17IuMAhlpPO9TfZ5VCRr26O1o1Fbv_2mkdKNme74OGAJMALqaGZ9aQEu2YE5a-aLvjjSHmd7GSopTX2E1zEfAkR-1_lM0YOR9BWUnE3cnjy0wujYg/s320/Screen+Shot+2012-10-14+at+2.18.39+AM.png" width="213" /></a></div>
<div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<div style="text-align: justify;">
<br />
Now i am going to discussed the last but not least feature of <span style="background-color: white; font-family: Courier, Consolas, monospace; font-size: 14px; text-align: justify;">SLComposeViewController</span> class. It is the completion handler. SLComposeViewController class define a block property of type SLComposeViewControllerCompletionHandler. SLComposeViewControllerCompletionHandler takes a parameter of type SLComposeViewControllerResult. Parameter indicate wether user finished or cancelled composing the post. Parameter will be one of following - </div>
<div style="text-align: justify;">
</div>
<div class="p1">
</div>
<ul>
<li>SLComposeViewControllerResultCancelled,<br /> It indicates that user has cancelled composing the post</li>
<li> SLComposeViewControllerResultDone<br /> It indicates that user has finished composing the post </li>
</ul>
<div>
<div style="border-color: green; border-style: groove; border-width: 4px;">
<pre class="brush: objc; toolbar: false;gutter: false;"> //add completion handler
twitterComposer.completionHandler = ^(SLComposeViewControllerResult result) {
if (result == SLComposeViewControllerResultCancelled) {
NSLog(@"User has cancled composing the post, and tapped the cancle button");
}
if (result == SLComposeViewControllerResultDone) {
NSLog(@"User has finished composing the post, and tapped the send button");
}
};
</pre>
</div>
<br />
To know more about block programming <a href="http://kmithi.blogspot.in/2012/03/blocks-programming-in-ios.html" target="_blank">check this!</a><br />
Thanks for reading!! Please leave your valuable suggestions!! Bye Bye !!</div>
</div>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/03540465319086699554noreply@blogger.com5tag:blogger.com,1999:blog-6912106156720688131.post-43839070533972773992012-08-30T07:02:00.000-07:002012-10-09T10:22:32.434-07:00iOS Application Directory Structure : Document, Cache and tmp<div dir="ltr" style="text-align: left;" trbidi="on">
Hello friends!!<br />
<br />
In this post i am going to talk about iOS application directory structure. iOS applications run in sandbox like environment that means Application (A) can not access the resources of Application(B). In more easy words i can say that a closed room is allocated to each Application where they have to eat and sleep, of course room is closed so they can not access resources of each other. However an Application can request Operating System( OS ) to run other Application. Following image shows directory structure of a typical iOS application.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlU9yiMS0z35-I13HkcWTIAQfx0H_x685pEEDqjdmF_5qriMAm_Wn_J2tJt2KYbuJtUvDi16VVw3zpDssrGvMgM3KlhdnXWJ7yLmWfg6fb5tQ_zJTmBc44ubFmRGtKWA9NuFctx8tDwa0/s1600/Screen+shot+2012-08-30+at+7.57.32+PM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlU9yiMS0z35-I13HkcWTIAQfx0H_x685pEEDqjdmF_5qriMAm_Wn_J2tJt2KYbuJtUvDi16VVw3zpDssrGvMgM3KlhdnXWJ7yLmWfg6fb5tQ_zJTmBc44ubFmRGtKWA9NuFctx8tDwa0/s400/Screen+shot+2012-08-30+at+7.57.32+PM.png" width="271" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: left;">
<a href="http://www.apple.com/" target="_blank">Apple</a> reserve all rights to change the directory structure and you may find different structure on different OS version for example "Libarary/ Application Support " does not exists in iOS 5 and older versions. Most important directories are app bundle(myApp.app), Document, cache and tmp. </div>
<div class="separator" style="clear: both; text-align: left;">
When our Application is installed on iPhone, iTunes creates a home directory(<span style="font-family: Courier New, Courier, monospace;">In above image "App" is home directory</span>) for application. This directory is same as closed room(ad discussed above) for the App. It contains everything that Application can access. Applications can create file, delete file under home directory. </div>
<div class="separator" style="clear: both; text-align: left;">
You should be selective while storing file in directories because wrong selection of directory may affect the iCloud syncing process and waste the user space, that encourage the user to delete your App. So you should be selective to where you place which file. </div>
<div class="separator" style="clear: both; text-align: left;">
iOS uses a unique ID instead of application name, so you can not give absolute or relative path of any directory. </div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJpa7dZ1HBAwjNksKyPpoaPr074-8tk-vc1TtlSTfKqxqUaSqBTUsTsqIZ6Bawivm7kiYXg4wxjM8_3pbrPYeWcZ4DGadb0dZKNZjIhFBVIienYhZ2s1f3JYJ-biy4jpfn4Juwedw11tw/s1600/Screen+shot+2012-09-17+at+11.33.17+PM.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="35" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJpa7dZ1HBAwjNksKyPpoaPr074-8tk-vc1TtlSTfKqxqUaSqBTUsTsqIZ6Bawivm7kiYXg4wxjM8_3pbrPYeWcZ4DGadb0dZKNZjIhFBVIienYhZ2s1f3JYJ-biy4jpfn4Juwedw11tw/s640/Screen+shot+2012-09-17+at+11.33.17+PM.png" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
Now let me describe the usage of directories and code to access these directories. </div>
<h3 style="text-align: left;">
<span style="color: #741b47;">Bundle Directory(myApp.app) -</span></h3>
<div>
This is the place(bundle) where your App exists. You should not modify this directory, it prevent your app from launching again. All resources you put in your project will stored in this directory. How to get the path of bundel directory -<br />
<pre class="brush: objc; toolbar: false;gutter: false;">//get the main bundel
NSBundle *bundle = [NSBundle mainBundle];
//get the path of home directory
NSString *bundlePath = [bundle bundlePath];</pre>
You can find the path of your resources by appending resource name to bundlePath or as follows</div>
<div>
<pre class="brush: objc; toolbar: false;gutter: false;">//Find the path of a image(myPhoto.png)
NSString *pathTomyPhoto = [[NSBundle mainBundle] pathForResource:@"myPhoto" ofType:@"png"];
NSLog(@"\n%@\n",pathTomyPhoto);
</pre>
</div>
<u><br /></u>
<u>OUTPUT-</u><br />
<span style="color: #0b5394;">.../Applications/99C1AFFA-0908-4968-B6C7-E2644385D86D/appName.app/myPhoto.png</span><br />
<br />
To protect this directory from tempering iOS sign it with unique id, any modification in this ID prevent your app from launching.<br />
<h3 style="text-align: left;">
<span style="color: #741b47;">Document Directory</span></h3>
<div>
Use this directory to store important files of your application like sqlite database. Data of this directory is backup in iTunes so don't store temporary and large fiels. If you will store large amount of data in document directory, Apple may reject your App <a href="http://stackoverflow.com/a/8209801/1079903" target="_blank">see this</a>. In more general you should store only those data which can not be recreated by your app. How to get the path of document directory?</div>
<div>
<br /></div>
<div>
<pre class="brush: objc; toolbar: false;gutter: false;">/*use following c function to find any directory, just you need to provide the directory type*/
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
//find the actual path
NSString* docDir = [paths objectAtIndex:0];
NSLog(@"\n%@\n",docDir);</pre>
<h3>
<span style="color: #741b47;">Document/Inbox Directory </span></h3>
<div>
<span style="color: #444444;">This directory is used by other applications to open files with the help of your application. For example email app places email attachement in inbox directory before opening the attachement with the help of your application. We have only read and delete permission on this directory means we can not create new file or edit fiels in this directory. If you want to edit any file, then you must move that file to document or other directory. You can access this directory by adding a path component "Inbox" to document directory path.</span></div>
<div>
<h3>
<span style="color: #741b47;">Library Directory</span></h3>
</div>
<div>
<span style="color: #444444;">This directory is used to store app specific files. Content of this directory is also backup in iTunes but not exposed to user. You should not store user specific files in directory. iOS applications are not permitted to use this directory although you can use the subdirectories of this directory. </span></div>
<div>
<span style="color: #444444;"><br /></span></div>
<div>
<span style="color: #0b5394;">NOTE: data of cache directory is not backup in iTunes. </span></div>
<div>
<br /></div>
<div>
<pre class="brush: objc; toolbar: false;gutter: false;">NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libDirectory = [paths objectAtIndex:0];
NSLog(@"%@",libDirectory);</pre>
</div>
<div>
<h3>
<span style="color: #741b47;">Library/Caches Directory</span></h3>
</div>
Content of this directory is not backup by the iTunes. You should store only those files which can be recreated easily. System may delete content of this directory (to free up the disk space) when it is required, so your app should gracefully handel this type of situations Eligible candidate of this directory are downloadable contents, database cache files etc . You can create, edit, delete content of this directory. You can get the path of cache directory as follows -<br />
<pre class="brush: objc; toolbar: false;gutter: false;">NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths objectAtIndex:0];
NSLog(@"%@",cachesDirectory);</pre>
<h3>
<span style="color: #741b47;">Library/Application Support Directory</span></h3>
This directory was introduced in iOS 5.0.1 and content of this directory is also backup in iTunes. You can use this directory to store App created fiels, templates for example we can store newly purchased levels of game in this directory. You can find the path of this directory by passing "NSApplicationSupportDirectory" as searchPathDirectory in "NSSearchPathForDirectoriesInDomains" method.<br />
<h3>
<span style="color: #741b47;">Library/Preferences Directory</span></h3>
Apple recommend us to not create any file in this directory and instead of this we should use "NSUserDefault" class to set and get preference values of our APP. Purpose of this directory is to store app preference files, generally our app creates files in this directory. You can set preference values in user default as follows -<br />
<pre class="brush: objc; toolbar: false;gutter: false;">//get user default object
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
//set values in user default
[userDefault setValue:@"mithi" forKey:@"nickname"];
[userDefault setBool:NO forKey:@"shoulShowDOB"];
[userDefault synchronize];
//get values from user default
NSString *nickName = [userDefault valueForKey:@"nickname"];
NSLog(@"Nickname = %@",nickName);
BOOL shouldShowDOB = [userDefault boolForKey:@"shoulShowDOB"];
if (shouldShowDOB) {
NSLog(@"We have permission to show DOB");
}else {
NSLog(@"We do not have permission to show DOB");
}
</pre>
</div>
<br />
<div>
<h3>
<span style="color: #741b47;">tmp Directory</span></h3>
</div>
Last but not least tmp directory is use to store temporary files, you should use this directory to store those files which are not required to persist or required for a few time. You should delete the files when that is not required. Content of this directory can be deleted any time. You can get the path of this directory as follows -<br />
<pre class="brush: objc; toolbar: false;gutter: false;">NSString *tmpDirectory = NSTemporaryDirectory();
NSLog(@"%@",tmpDirectory);
</pre>
<br />
Don't forget to leave your valuable comments!! bye bye!!</div>Anonymoushttp://www.blogger.com/profile/03540465319086699554noreply@blogger.com3tag:blogger.com,1999:blog-6912106156720688131.post-64464527661476743582012-03-23T06:30:00.001-07:002012-10-09T10:32:19.653-07:00Blocks Programming in iOS<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
Hello friends!!<br />
In this post i am going to talk about<span style="color: #0b5394;"> </span><span style="color: blue;">"Blocks programming in iOS".</span> iOS4 and latter supports blocks programming.<br />
<br />
<b><span style="color: blue; font-family: 'Courier New', Courier, monospace;">Blocks:</span></b><br />
<span style="font-family: 'Courier New', Courier, monospace;"> Blocks are code snippet that can be use as a function or can be written as inline code at time of method invocation.</span><br />
<br />
I think defining blocks is wasting of time because i can not define whole thing about blocks as it has lots of features , lots more than the above definition. You will get good understanding of blocks programming by examples of course! because examples are good way to explain anything.Let's start<br />
<br />
<span style="color: blue; font-family: 'Courier New', Courier, monospace;">Syntax to declare inline block:</span><br />
<br />
<pre class="brush: objc; gutter: false; toolbar: false;">^(parameter list){
//you code
}
</pre>
<br />
Inline block means blocks defined at time of function call.Caret (^) indicate the start of block literal and curly braces {} indicate the body of block.For example -<br />
<pre class="brush: objc; gutter: false; toolbar: false;">//following method use the block to print the square of given number
-(void)printSquareOf:(NSInteger)number byExecutingBlock:(int(^)(int))block{
NSLog(@"Square of %i = %i",number,block(number));
//you can call block same as c functions
//syntax to call block using block name - blockName(commas separated parameter list)
//like block(number); block1() and so on
}
//call above method to print the square fo desire number
//block will square the given number and called method will print result in log
[self printSquareOf:4 byExecutingBlock:^(int n){return n*n;}];
</pre>
<span style="background-color: #f9cb9c;">OUTPUT: </span><br />
<span style="background-color: #f9cb9c;"> <b>Square of 4 = 16 </b></span><br />
<br />
We have define a inline block at line number 13 which take a integer as parameter and returns square of that number and "<span style="color: #3d85c6;">printSquareOf: byExecutingBlock: </span>" prints the result.You can declare block as function argument like -<br />
<br />
<div class="p1">
<i><span style="font-family: 'Courier New', Courier, monospace;">(return_type(^)(parameters list))block_name</span></i></div>
<div class="p1">
For examples -</div>
<div class="p1">
</div>
<div class="p1">
<span style="color: #6fa8dc; font-family: Times, 'Times New Roman', serif;"><i>-(<span class="s1">void</span>)myLog:(<span class="s1">void</span>(^)())block;</i></span></div>
<div class="p1">
</div>
<div class="p1">
<span style="color: #6fa8dc; font-family: Times, 'Times New Roman', serif;"><i>-(<span class="s1">void</span>)printSquareOf:(<span class="s2">NSInteger</span>)number byExecutingBlock:(<span class="s1">int</span>(^)(<span class="s1">int</span>))block;</i></span></div>
<div class="p1">
<span style="font-family: Times, 'Times New Roman', serif;">We need to writes inline blocks again and again, thats not good, now question is how can we writes once and use many times? of course we can do it by assigning blocks to a block variable, call blocks using block variable. </span></div>
<div class="p1">
<span style="color: blue; font-family: 'Courier New', Courier, monospace;">Syntax to declare a block Variable -</span></div>
<div class="p1">
<code class="objc datatypes"> returnType</code> <code class="objc plain">(^blockVariableName)(parametersTypeList</code><code class="objc plain">);</code><span style="font-family: Times, 'Times New Roman', serif;"><br /></span></div>
<div class="p1">
<code class="objc plain">For example - </code></div>
<div class="p1">
<code class="objc plain"><span style="font-family: 'Courier New', Courier, monospace;"> void(^now)(void);</span></code></div>
<div class="p1">
<code class="objc plain"><span style="font-family: 'Courier New', Courier, monospace;">
</span></code></div>
<div class="p1">
<code class="objc plain"><span style="font-family: 'Courier New', Courier, monospace;"> void<span class="s1">(^doSquare)(int</span><span class="s1">);</span></span></code></div>
<div class="p1">
<code class="objc plain"><span style="font-family: 'Courier New', Courier, monospace;">
</span></code></div>
<div class="p1">
<code class="objc plain"><span style="font-family: 'Courier New', Courier, monospace;"><span class="s1"> void</span>(^sayHelloTo)(<span class="s2">NSString</span>*);</span></code></div>
<div class="p1">
<code class="objc plain"><br /></code></div>
<div class="p1">
<code class="objc plain"><span style="color: blue; font-family: 'Courier New', Courier, monospace;">Syntax to assign block literal to block variable -</span></code></div>
<div class="p1">
<code class="objc plain"> blockName = ^(parameterList){};</code></div>
<div class="p1">
<code class="objc plain"><br /></code></div>
<div class="p1">
<span style="font-family: Times, 'Times New Roman', serif;">Following example shows that how to declare block variables and assign block literal in two different steps</span><br />
<span style="font-family: Times, 'Times New Roman', serif;"><br /></span></div>
<pre class="brush: objc; gutter: false; toolbar: false;"> //declare block variable
void(^sayHello)(void);//sayHello is block variable name
//assign block literal to block variable sayHello
sayHello = ^{NSLog(@"Hello,I am coding for bugs");};
//call block using block variable
sayHello();
</pre>
In above example we have declare block variable at line number 2 which return type is void, name is "sayHello" and it does not accept any parameter so void in parameter list. We have assigned block literal at line number 4 which print "Hello,I am coding for bugs". We are calling block at line number 7.<br />
<br />
<div class="p1">
<code class="objc plain"><span style="color: blue; font-family: 'Courier New', Courier, monospace;">In one shot we</span><span style="color: blue; font-family: 'Courier New', Courier, monospace;"> can declare block variable and assign block literals like this -</span> </code></div>
<div class="p1">
<code class="objc plain"> <code class="objc datatypes">returnType</code><span style="font-family: Times;"> </span><code class="objc plain">(^blockVariableName)(parameterTypeList</code><code class="objc plain">) = </code>^(parameterList){};</code></div>
<br />
Following example shows that how to declare block variable and assign block literal in one shot -<br />
<pre class="brush: objc; gutter: false; toolbar: false;"> //this block calculate factorial of given number
NSInteger(^calculateFactorialOf)(NSInteger) = ^(NSInteger n){
NSInteger fact = 1;
if (n==0) {//factorial of 0 is 1
return fact;
}
for (int i=n; i>0; i--) {
fact = fact*i;
}
return fact;
};
//call block, factorial will be assign to result
NSInteger result = calculateFactorialOf(4);
NSLog(@"factorial = %i",result);//print 24
</pre>
In above example you have seen how to use inline block and block variables.One main thing left about block is - it captures surrounding state that's why it is called as closures. Blocks are called closures because they are closed around variables that are in scope at the time of block declaration. Its means that a variable declare before of block declaration can be directly used in block.Block keeps a read only copy of in scope variables for example -
<br />
<pre class="brush: objc; gutter: false; toolbar: false;">//calculate half of the given number using provided block and print the result
-(void)calculateHalfOf:(NSInteger)number byExecutingBlock:(int(^)(int))block{
NSLog(@"Half of %i = %i",number,block(number));
//you can call block same as c functions
//syntax to call block using block name - blockName(commas separated parameter list)
//like block(number); block1() and so on
}
//cal the calculate method from viewDidLoad: method
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSInteger divider = 2;
[self calculateHalfOf:4 byExecutingBlock:^(int n){return n/divider;}];
//above block will carry a read only copy of divider variable
}
</pre>
<span style="background-color: #f9cb9c;">OUTPUT: </span><br />
<span style="background-color: #f9cb9c;"> Half of 4 = 2 </span><br />
<br />
In above block we have not define the <span style="color: blue;">divider</span> variable but we are using we can't modify the value of divider if we will do that it will give error as -<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKoLjSMcQZdgtLkay_TU4ZT8WyhflswHaqmcjqDZOmnNcnC6IE0_E-iH8bs8OlKPtWiEN7xOBTxFC0L_scp76Xicherc1OHctAswXKCuiOYp6bhYg8cvf6IWOmY63jNB5q77LzSitrl6s/s1600/Screen+shot+2012-03-23+at+5.17.03+PM.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKoLjSMcQZdgtLkay_TU4ZT8WyhflswHaqmcjqDZOmnNcnC6IE0_E-iH8bs8OlKPtWiEN7xOBTxFC0L_scp76Xicherc1OHctAswXKCuiOYp6bhYg8cvf6IWOmY63jNB5q77LzSitrl6s/s1600/Screen+shot+2012-03-23+at+5.17.03+PM.png" /></a></div>
<br />
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
In above screenshot we can see that error - <span style="color: red;"><i>Variable is not assignable(missing <span class="s1">__block</span> type specifier).</i></span></div>
<div style="text-align: left;">
Oh! Its not good, What will we do?if need to modify the <span style="color: blue;"><i>divider</i></span> variable. Don't worry take long breath and think what is <span style="color: blue;">__block</span>? Yeah you are thinking right by using <span style="color: blue;">__block </span> storage type modifier we can make <span style="color: blue;">divider</span> mutable.For example -</div>
<pre class="brush: objc; gutter: false; toolbar: false;">- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
__block NSInteger divider = 1;//__block makes variable mutable
//see the above example for calculateHalfOf: byExecutingBlock: definition
[self calculateHalfOf:4 byExecutingBlock:^(int n){
//modify divider, now it is not read only
divider = divider*2;
return n/divider;}];
}
</pre>
<span style="background-color: #f9cb9c;">OUTPUT: </span><br />
<span style="background-color: #f9cb9c;"> Half of 4 = 2 </span><br />
<br />
When we use __block storage type modifier, variables passed by reference into the block.<br />
<div style="text-align: justify;">
<span style="color: #cc0000; font-family: 'Courier New', Courier, monospace;"><i>Note: We should not use __block causally because it moves variables to heap, so please do not use it unless you really need it.</i></span></div>
Hey cheers! We have completed basic of block programming.I can't believe that still you guys are reading! I salute your enthusiasm.Now i am going to discuss last things.<br />
<b><span style="color: blue;">Declare block as property:</span></b><br />
<b><br />
BlockDemo.h
</b><br />
<pre class="brush: objc; gutter: false; toolbar: false;">#import<uikit/uikit.h>
typedef int (^devideEquallyBlock)(int);
@interface BlockDemo : UIViewController<uitextfielddelegate>{
devideEquallyBlock callbackBlock;
}
@property (nonatomic, copy) devideEquallyBlock callbackBlock;
-(void)calculateHalfOf:(NSInteger)number byExecutingBlock:(devideEquallyBlock)block;
@end
</uitextfielddelegate></pre>
<b>BlockDemo.m
</b><br />
<pre class="brush: objc; gutter: false; toolbar: false;">#import "BlockDemo.h"
@implementation BlockDemo
@synthesize callbackBlock;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
__block NSInteger divider = 1;//__block makes variable mutable
//assigning block to property
callbackBlock = ^(int n){
divider = divider*2;
return n/divider;};
[self calculateHalfOf:4 byExecutingBlock:callbackBlock];
}
-(void)calculateHalfOf:(NSInteger)number byExecutingBlock:(devideEquallyBlock)block{
NSLog(@"Half of %i = %i",number,block(number));
//you can call block same as c functions
//syntax to call block using block name - blockName(commas separated parameter list)
//like block(number); block1() and so on
}
- (void)dealloc {
[callbackBlock release];
[super dealloc];
}
@end
</pre>
In .h file i have used <span style="color: blue;">typedef</span>, it is a c construct that assign a name to existing data type.For example i have given a new name <span style="color: blue;">devideEquallyBlock</span> to block type "<span style="color: blue; font-family: 'Courier New', Courier, monospace;">(int<span class="s1">(^)(</span>int<span class="s1">))</span></span>". Even Apple uses <span style="color: blue;">typedef</span> to assign names to block because it keeps our code clean and readable.We should also use <span style="color: blue;">typedef</span>.I have released block at line number 27 in .m file because i have called copy at time of property declaration at line number 6 in .h file.<br />
<br />
Thanks for reading, please leave your comments below,bye bye! </div>
</div>
Anonymoushttp://www.blogger.com/profile/03540465319086699554noreply@blogger.com1tag:blogger.com,1999:blog-6912106156720688131.post-33243740995874072472012-03-21T06:21:00.000-07:002012-10-09T10:27:52.768-07:00Sharing data among iOS applications using UIPasteboard<div dir="ltr" style="text-align: left;" trbidi="on">
Hello Friends,<br />
<div>
As iOS apps have their own sandbox and one app can't read data of other application, for security reason its look good and really its good.One day i got a requirement in which i need to share data of one app with other app.First i thought it is not possible in an environment like sandbox, i searched on google and got a luck on <a href="http://stackoverflow.com/" target="_blank">stackoverflow</a> saying use UIPasteboard but a programmer like me expect some code. That day i did not get any thing more than a little luck saying don't worry it is possible using UIpasteboard so in this post i am going to talk about UIPasteboard and write some basic codes.<br />
<div>
<br /></div>
<div>
<span style="color: blue; font-family: 'Courier New', Courier, monospace;">UIPasteboard:</span></div>
<div>
<span style="font-family: 'Courier New', Courier, monospace;"> UIPasteboard is a class given in UIKit.framework.You can use it to share data within the application and with other applications.</span></div>
<div>
<br /></div>
<div>
I am using two application to demonstrate the use of UIPasteboard.</div>
<div>
<ol style="text-align: left;">
<li>PBWriter</li>
<li>PBReader </li>
</ol>
</div>
<div>
let's create first application named as PBWriter or you can name something else.This application take some input from user and save those in UIPasteboard.User Interface of this application look like this - </div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfRkvA_2FTNO1N0GD0JJgrTHZpJvwL939_Ko353wxUVvPeEedzGJamrhPfKcWIOAtyTds5HcA4H4JFOsCaxlcbFsd3WctmK8nU37kb_RrR296aYuT3-6Rjw44jeQ7uY_QdAI0h7gzWCsE/s1600/Screen+shot+2012-03-05+at+7.06.49+PM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfRkvA_2FTNO1N0GD0JJgrTHZpJvwL939_Ko353wxUVvPeEedzGJamrhPfKcWIOAtyTds5HcA4H4JFOsCaxlcbFsd3WctmK8nU37kb_RrR296aYuT3-6Rjw44jeQ7uY_QdAI0h7gzWCsE/s320/Screen+shot+2012-03-05+at+7.06.49+PM.png" width="156" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Enter data in above fields, hit "Save in PB" button it will save the data in Pasteboard.Oh! i have not discussed any thing about code. let's write code -</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
You can use any of following methods to create/get Pasteboard object, i am using "<span style="color: blue;">pasteboardWithName:create:</span>"</div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<ul style="text-align: left;">
<li>+generalPasteboar //<span style="color: #3d85c6;">use this to get system pasteboard</span></li>
<li>+pasteboardWithName:create: //<span style="color: #6fa8dc;">use this to create your own pasteboard</span></li>
</ul>
<div>
<div class="p1">
<span class="s1">
</span></div>
<div class="p1">
<span class="s1"><span style="color: #6fa8dc;"><br /></span></span></div>
<div class="p1">
<span class="s1"><span style="color: #6fa8dc;">/<span style="font-family: 'Courier New', Courier, monospace;">/use <span style="background-color: white;">reverse DNS notation</span> to keep you Paste board unique </span></span></span></div>
<div class="p1">
<span style="font-family: 'Courier New', Courier, monospace;"><span class="s1">NSString</span><span class="s2"> *PBNAME = </span>@"com.codingForBugs.PBDemo.PBDemo"<span class="s2">;</span></span></div>
<div class="p1">
<span style="font-family: 'Courier New', Courier, monospace;"><br /></span></div>
<br />
<div class="p1">
<span style="font-family: 'Courier New', Courier, monospace;"><span class="s1"> </span><span class="s2">UIPasteboard</span><span class="s1"> *pb = [</span><span class="s2">UIPasteboard</span><span class="s1"> </span><span class="s3">pasteboardWithName</span><span class="s1">:</span><span class="s4">PBNAME</span><span class="s1"> </span><span class="s3">create</span><span class="s1">:</span><span class="s5">YES</span><span class="s1">];</span><span style="color: #6fa8dc;">//create a new PB if does not exists </span></span></div>
<div class="p1">
<span style="color: #6fa8dc;"><br /></span></div>
<div class="p1">
By default custom pasteboards are not persistent, you need to make it manually.If not required in your case just ignore it.</div>
<div class="p1">
<br /></div>
<div class="p1">
<span style="font-family: 'Courier New', Courier, monospace;"><span style="color: #6fa8dc;">//pass yes to make pasteboard persistent</span> </span></div>
<div class="p1">
</div>
<div class="p1">
<span style="font-family: 'Courier New', Courier, monospace;"><span class="s1">[pb </span>setPersistent<span class="s1">:</span><span class="s2">YES</span><span class="s1">];</span></span></div>
<div class="p1">
<span class="s1"><br /></span></div>
<br />
<div class="p1">
If you are not setting Persistent property to YES, remamber that pastboard will be removed when your application quit.Now we have pasteboard and we need to write user information in it.<br />
<br />
<b><i><span style="color: #cc0000;">Note:Pasteboard will be removed when application uninstalled not matter it is persistent or not. </span></i></b><br />
<br />
There are some predefine properties in which you can write your data like <span style="color: blue;">string, strings, url,image, items </span>etc.For example you have only one string you can use "string" property of UIPasteboard. If you want to save more than one item than better to use items properties like -
<br />
<pre class="brush: objc; gutter: false; toolbar: false;"> NSMutableArray *pbValues = [[NSMutableArray alloc] init];
NSDictionary *d1 = [NSDictionary dictionaryWithObject:name.text forKey:@"name"];
NSDictionary *d2 = [NSDictionary dictionaryWithObject:s1Value.text forKey:@"dob"];
NSDictionary *d3 = [NSDictionary dictionaryWithObject:s2Value.text forKey:@"age"];
NSDictionary *d4 = [NSDictionary dictionaryWithObject:s3Value.text forKey:@"height"];
[pbValues addObject:d1];
[pbValues addObject:d2];
[pbValues addObject:d3];
[pbValues addObject:d4];
//save all items in pasteboard
[pb setItems:pbValues];</pre>
When you will hit "Save in PB" it call a method "saveButtonClicked:", this method look like this
<br />
<pre class="brush: objc; gutter: false; toolbar: false;">- (IBAction)saveButtonClicked:(id)sender {
//get paste board
UIPasteboard *pb = [UIPasteboard pasteboardWithName:PBNAME create:YES];//create a new PB if does not exists
//make PB persistent. PB will be deleted when its owner application uninstalled
[pb setPersistent:YES];
//save values in PB with unique key so thet other application can read it
NSLog(@"name = %@",name.text);
NSMutableArray *pbValues = [[NSMutableArray alloc] init];
NSDictionary *d1 = [NSDictionary dictionaryWithObject:name.text forKey:@"name"];
NSDictionary *d2 = [NSDictionary dictionaryWithObject:nameValue.text forKey:@"dob"];
NSDictionary *d3 = [NSDictionary dictionaryWithObject:ageValue.text forKey:@"age"];
NSDictionary *d4 = [NSDictionary dictionaryWithObject:heightValue.text forKey:@"height"];
[pbValues addObject:d1];
[pbValues addObject:d2];
[pbValues addObject:d3];
[pbValues addObject:d4];
//save all items in pasteboard
[pb setItems:pbValues];
}
</pre>
</div>
</div>
<br />
<div class="separator" style="clear: both; text-align: left;">
<i><u><span style="color: #351c75;">If you calls setItems: again, it overwrites previous values to prevent it use <span style="background-color: white; font-family: Courier, Consolas, monospace; font-size: 13px;">addItems: as [pb addItems:newValues]</span></span></u></i></div>
<div class="separator" style="clear: both; text-align: left;">
Now we have finish the writer part we need to write a reader application that will read the data save in pasteboard. Reader app ui look like this - </div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUWBFTdf0ToOGlkuNm1YC3gusWfScmtXVB-pVBKxeRl4pmCE0GhiG7jOaW52QPfvLizaq169Hv05fX20N976s6kCaV2ZMIjiBHx5wTJ2l83Aw7a7pmySuBWs4nXE6liAN-3ZNUYkZk7P4/s1600/Screen+shot+2012-03-21+at+4.21.02+PM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUWBFTdf0ToOGlkuNm1YC3gusWfScmtXVB-pVBKxeRl4pmCE0GhiG7jOaW52QPfvLizaq169Hv05fX20N976s6kCaV2ZMIjiBHx5wTJ2l83Aw7a7pmySuBWs4nXE6liAN-3ZNUYkZk7P4/s320/Screen+shot+2012-03-21+at+4.21.02+PM.png" width="162" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
When you will hit the "Read PB" button one pop-up will come displaying whatever information we have saved in pasteboard.To read data first we need to get the pasteboard, we will retrieve dat using any of following function - </div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<div class="p1">
</div>
<ul style="text-align: left;">
<li>dataForPasteboardType:</li>
<li>string</li>
<li>strings</li>
<li>items and so on </li>
</ul>
<br />
<br />
<div class="separator" style="clear: both; text-align: left;">
Data will be returned in form of NSData and of particular type same as properties. For example if you are assigning value to string property it will return string, when we access using other method, we need to convert it in string from NSData. When you will hit "Read PB" button "- (<span class="s1">IBAction</span>)readPB:(<span class="s1">id</span>)sender" called this method look like this -</div>
<pre class="brush: objc; gutter: false; toolbar: false;">- (IBAction)readPB:(id)sender {
//get pasteboard with predefine name
UIPasteboard *pb = [UIPasteboard pasteboardWithName:PBNAME create:NO];//no because we doesn't want to create a new one
if (pb) {
NSArray *dataArray = [pb items];
NSDictionary *name = [dataArray objectAtIndex:0];
//valuesInPb use to create message text
NSString *valuesInPb = [NSString stringWithFormat:@"Name = %@\n",
[[NSString alloc] initWithData:[name valueForKey:@"name"] encoding:NSUTF8StringEncoding]];
NSDictionary *info = [dataArray objectAtIndex:1];
valuesInPb = [NSString stringWithFormat:@"%@D.O.b = %@\n",valuesInPb,
[[NSString alloc] initWithData:[info valueForKey:@"dob"] encoding:NSUTF8StringEncoding]];
NSDictionary *info1 = [dataArray objectAtIndex:2];
valuesInPb = [NSString stringWithFormat:@"%@Age = %@\n",valuesInPb,
[[NSString alloc] initWithData:[info1 valueForKey:@"age"] encoding:NSUTF8StringEncoding]];
NSDictionary *info2 = [dataArray objectAtIndex:3];
valuesInPb = [NSString stringWithFormat:@"%@Height = %@\n",valuesInPb,
[[NSString alloc] initWithData:[info2 valueForKey:@"height"] encoding:NSUTF8StringEncoding]];
[self showText:valuesInPb target:self];
NSLog(@"%i",[dataArray count]);
}else{
[self showText:@"PB doesn't exists.\nYou should run PBWritter app first" target:self];
}
}
//this method is use to display the alert vew
-(void)showText:(NSString*)textMessage target:(id)target{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"pbReader" message:textMessage delegate:target cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
</pre>
<div class="separator" style="clear: both; text-align: left;">
I think it may help you, plese leave you comments.bye bye!</div>
</div>
</div>Anonymoushttp://www.blogger.com/profile/03540465319086699554noreply@blogger.com15tag:blogger.com,1999:blog-6912106156720688131.post-73720502198285239142012-02-26T02:05:00.002-08:002012-10-10T12:23:10.691-07:00Callling Web services in PhoneGap<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="font-family: Arial,Helvetica,sans-serif; text-align: justify;">
Hello Friends!! Now a Days PhoneGap getting fame and used by a lots of developer. I have done my very first PhoneGap application and i want to share my experience, so in this blog I am going to talk about PhoneGap and web services more frankly <b>How to call a web service in PhoneGap or javascript?</b></div>
<div style="font-family: "Courier New",Courier,monospace; text-align: justify;">
<br /></div>
<div style="font-family: "Courier New",Courier,monospace; text-align: justify;">
<b> <span style="color: blue;">PhoneGap:</span></b></div>
<div style="font-family: "Courier New",Courier,monospace; text-align: justify;">
<b> </b>It is a cross platform framework to develop mobile application using web technologies like - HTML,javaScript,css.</div>
<div style="font-family: "Courier New",Courier,monospace; text-align: justify;">
<br /></div>
<div style="font-family: "Courier New",Courier,monospace; text-align: justify;">
<b style="color: blue;">Web Services:</b></div>
<div style="text-align: justify;">
<div style="font-family: 'Courier New',Courier,monospace;">
Web services are methods hosted and executed by server. Electronic devices use it to communicate to server.It remove the platform dependency of devices that means a device running iOS can communicate with a device running Linux/Mac etc.</div>
<div style="font-family: 'Courier New',Courier,monospace;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<i>I assume that you have installed the PhoneGap and created a demo application to test- How to call a web service using javaScript?If not please create a demo application or you may use your original application.</i><br />
<i> </i><i> </i><br />
Now we are going to write code to call web services</div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br />
Create a file named as xui-<version number>.js, paste api code from link <a href="http://xuijs.com/downloads/xui-2.3.2.js" target="_blank">http://xuijs.com/downloads/xui-2.3.2.js </a> place xui-2.3.2.js in desired folder inside www folder, you can creates a folder called api. I use api folder to put all apis at one place.You can include xui api as follow -<br />
<pre class="brush: javascript; gutter: false; toolbar: false"><script src="api/xui-2.3.2.js" type="text/javascript">
</script>
</pre>
</div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<div class="p1">
<span style="background-color: white; color: #6aa84f;">We have included api, now we need to write javaScript function to call web service, i am using a separate function because it will keep my code clean and clear and we can reuse it easily or call on a particular event.</span><br />
<span style="background-color: white; color: #6aa84f;"><br /></span></div>
</div>
<div style="font-family: 'Courier New',Courier,monospace;">
</div>
<pre class="brush: javascript; gutter: false; toolbar: false">function callWebService(){
//create url
var url = "http://search.twitter.com/search.json?q=PhoneGap&rpp=1";
x$.data = {};
x$("#search_tweet_button").xhr(url,{
error: function(){alert("failed"+this.responseText)},
callback: function(){
var jsonResponse = eval("("+this.responseText+")");
var tweets = jsonResponse.results;
if(tweets.length>0){
x$("#tweet").html(tweets[0].text);
}
}
});//end of xhr
}//end of method
</pre>
<div style="font-family: Arial,Helvetica,sans-serif;">
xhr(url,{ callback:{ }}); method is use to access web services, function defined in front of error will get called when some error occurred while processing the request in other words if response code is not 200 and callback will be called on success of request.If you will not specify callback then response text will be inserted in html element, in this case "search_tweet_button".</div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
eval("("+this.responseText+")"); is used to get correct json object.</div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div>
<div style="color: blue; font-family: Arial,Helvetica,sans-serif;">
<i>tweetsPage.html</i></div>
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i><html></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> <head></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> <title></title></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> <script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> <script type="text/javascript" src="api/xui-2.3.2.js"></script></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> <script type="text/javascript" charset="utf-8"></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> function callWebService(){</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> //create url </i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> var url = "http://search.twitter.com/search.json?q=PhoneGap&rpp=1";</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> x$.data = {};</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> x$("#search_tweet_button").xhr(url,{</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> error: function(){alert("failed"+this.responseText)},</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> callback: function(){</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> var jsonResponse = eval("("+this.responseText+")");</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> var tweets = jsonResponse.results;</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> if(tweets.length>0){</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> x$("#tweet").html(tweets[0].text);</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> }</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> }</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> });//end of xhr</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> }//end of method</i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> </script></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> </head></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> <body></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> <h1 style="color:green;">Tweets Page</h1></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> <div id ="tweet" style="color:blue;">tweet will come here</div></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> <button type="button" onclick="callWebService()" id="search_tweet_button">Search Tweets</button></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i> </body></i></span><br />
<span style="background-color: white; color: #222222; font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 18px;"><i></html> </i></span></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<div class="p1">
<br /></div>
<div style="color: #6aa84f; font-family: Verdana,sans-serif;">
<span style="background-color: white; color: red; font-family: Arial, Helvetica, sans-serif;">Note : set ExternalHosts value as * in PhoneGap.plist file other wise it may not work for you.</span></div>
</div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div class="separator" style="clear: both; font-family: Arial,Helvetica,sans-serif;">
</div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHkjLCTof-57_-DAl9w05O9uiSCAXj0oEVsJQz_Muz5xwKpfwNI6Fh0Rv8zhfyA8caEl4yrMomO22sj9Nz5OXaUvbXLwp3dSgTbT353s7Ltr9wNfIhworhBSfon45RUnWaaZN7vEndX0M/s1600/Screen+shot+2012-02-26+at+4.37.22+PM.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHkjLCTof-57_-DAl9w05O9uiSCAXj0oEVsJQz_Muz5xwKpfwNI6Fh0Rv8zhfyA8caEl4yrMomO22sj9Nz5OXaUvbXLwp3dSgTbT353s7Ltr9wNfIhworhBSfon45RUnWaaZN7vEndX0M/s400/Screen+shot+2012-02-26+at+4.37.22+PM.png" width="202" /></a></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgB8JwlWtVAmsl86e5ey3hJxM7GDdQoREdWf5ZGZohdyWEJb5RnSjTZjo4XLADfum9A1kTEkglWRdQ6btR1WxQU_g2fEAiwZ9K2979W-dESoppVbIW8IOi3z3PXObHr3EP-YFcH1t5OEw8/s1600/Screen+shot+2012-02-26+at+4.37.39+PM.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgB8JwlWtVAmsl86e5ey3hJxM7GDdQoREdWf5ZGZohdyWEJb5RnSjTZjo4XLADfum9A1kTEkglWRdQ6btR1WxQU_g2fEAiwZ9K2979W-dESoppVbIW8IOi3z3PXObHr3EP-YFcH1t5OEw8/s400/Screen+shot+2012-02-26+at+4.37.39+PM.png" width="205" /></a></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<br /></div>
<div style="font-family: Arial,Helvetica,sans-serif;">
<span style="color: blue;"><br />
</span><br />
<span style="color: blue;"><br />
</span><br />
<span style="color: blue;"><br />
</span><br />
<span style="color: blue;">Example of post request :</span><br />
<span style="color: blue;"></span></div>
<div style="color: blue; font-family: Arial,Helvetica,sans-serif;">
</div>
<pre class="brush:javascript; gutter: false; toolbar: false">function callWebService(){
var url = "http://example.com/webser/xyzWebService/?&contentId=170;
x$.data = {};
x$("#html_element_name").xhr((url),
{ method:'post',
headers:{'Content-Type':'application/xml'},
data:'<searchparameters><searchletter> PhoneGap </searchletter></searchparameters>',
error: function(){//handle errors here },
callback: function(){
//do whatever you want
//you can access response text as "this.responseText"
}
});
}
</pre>
<div style="font-family: Arial,Helvetica,sans-serif;">
</div>
<div style="color: blue; font-family: Arial,Helvetica,sans-serif;">
If you are setting Content-Type then you should comment the default content- type value in xui.js it was giving error for me.If your is OK, ignore it.</div>
<pre class="brush:javascript; gutter: false; toolbar: false">if (method.toLowerCase() == 'post') {
//req.setRequestHeader('Content-Type','application/json');
;
}
</pre>
<div style="font-family: Arial,Helvetica,sans-serif;">
If this blog is useful, please leave your comments. bye bye!!<br />
<br />
Download <a href="http://dl.dropbox.com/u/75974054/phonegap.zip" target="_blank">Android Source Code</a> developed by my friend <a href="http://in.linkedin.com/pub/ajay-sharma/40/726/b59" target="_blank">Ajay Sharma</a>.<br />
<br />
<a href="http://www.blogger.com/"></a></div>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/03540465319086699554noreply@blogger.com40