Showing posts with label ios. Show all posts
Showing posts with label ios. Show all posts

Friday, 28 April 2017

Typescript Plugin For Netbeans IDE

Netbeans is one of my favorite IDE, and i use it for coding ionic apps. And here is the plugin that i used in netbeans to write TypeScript Download

Tuesday, 5 April 2016

How to generate IPA file without Provisioning profile or developers account using xcode 7 for distribution

Hi friends recently I had to build an ios accounting app for one of my client. The ios simulator is great! and by xcode 7 i was also able to test the app in real device. But after successful completion of the project I was really shocked that I had to pay $99 to generate an IPA file for distribution. The overall price that i charged from my client is only $60 and how come it be feasible to pay such a huge amount for a simple app. And finally I was able generate ipa without spending even a single dollar.


How I Generated IPA file: 
1> Connect Your Iphone to To Your Mac.
2> Open your ios Xcode project(mine is XCode 7).
3> change products-Destination to your connected device(i not connected change it to 'ios device').
4> press cmd+B to build your project.
** After Completion of Build Task you will find YourAppName.app file under the Products folder in your XCode project navigator.
5> Right click on the YourAppName.app and click on show in finder option. Finder will appear with the particular file, Just copy it.
6> Create a new folder in your desktop and rename it to Payload and paste the particular file it.
7> Compress zip the folder(Payload.zip) and rename it to Payload.ipa.
** Now You have the IPA file in your hand, and now you could distribute it to as many clients you want without any restriction.

How I Installed it in my Client's Iphone:
1> Download ifunbox in addition to iTunes
2> Connect your Device to your Computer
3> Open ifunbox, select your device, then click on install app and select the previously generated IPA file.
Done

Its Not Completed Yet! when you try to open your app in  your Iphone you will get this Untrested App Developer notification,

How to Avoid Untrested App Developer Notification:

For ios version less than 9.2:
Goto settings-general-profile, select the developer Apple Id and click on trust.

For ios version 9.2:
Goto Settings-General-Device Management and click on your Apple ID and tap on Trust option.

Thats all Now you could use your app as usual!

Saturday, 17 October 2015

IOS: Executing a function in main queue using swift

      Sometimes our application will have multi queues, if so then you will have to be more careful about running your code on respective queues since a code that has to be run on a main queue wont run on another queues; mainly background queues. In this tutorial you're gonna learn how to send the codes to main queue from an another in swift for your ios app. 

      If you want to achieve something in your main queue(thread) from a background queue add the below code to you background queue. consider a case that you wont be able to show alert (which has to run on a main queue) from the dataTaskWithRequest() as it works on an another queue and here you have to call the alert from inside the below code.

Swift:
dispatch_async(dispatch_get_main_queue()) { () -> Void in  
 // add your code here  
 }  

Its really simple with swift isn't it!

IOS: Perform the segue programmatically

      In most of your ios apps you will be having more than one window and will also have cases that you want to switch from your current viewController to another viewController. you could achieve it by just ctrl+dragging from your button in first viewController to second view control and selecting 'show' option from the popup menu.

      But their are cases when you want to segue from one to another programatically without a button click. In such cases you will have to ctrl+drag from the first viewController to second viewController and select 'show' option from the popup menu and set an identifier for the newly added segue. And now you have to copy past the below code to your programe where you want to perform the segue programmatically. Dont forget to replace the identifier in the sample code with your segue identifier or else the app will crash.

Swift:
 self.performSegueWithIdentifier("<Segue_Identifier>" ,sender: self)  

If it doesn't work then try:
 self.shouldPerformSegueWithIdentifier("<Segue_Identifier>" ,sender: self)  

Its really cool with swift isn't it!


IOS: Showing alert in ios apps using swift

         Most of the mobile apps will be having an alert to show different kinds of messages such as to show offers, report errors, to remind about empty text fields and etc.. In this tutorial youre gonna learn how to show alert in your ios app using swift. 

         In the below code replace 'TITLE' with your alert box title and 'DESCRIPTION' with your alert message.Also you could add your custom code to be executed when the user presses the 'OK' button.

Swift:
let myAlert = UIAlertController(title: "TITLE", message: "DESCRIPTION", preferredStyle: .Alert)  
               var actionOnOk = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {  
                 UIAlertAction in  
               //add your code here to execute while clicking ok button  
               }  
               myAlert.addAction(actionOnOk)  
               self.presentViewController(myAlert, animated: true, completion: nil)  

IOS: Creating a login in ios using swift and backend with php Mysql

        The use of login page will be necessary when you limit the user access to you app for only registered users. In this tutorial we are going to post an http request to the server and get the response and process it.
        You will have to create three php pages to handle the server side, you could collect the code for the php pages from my last ios post: Make an http request from the ios device using swift and also receiving a response as a json array from the server-side PHP Mysql.



Swift:
 func post() {  
   var username="USERNAME" //replace with your username  
      var password="PASSWORD" //replace with your password  
   var session = NSURLSession.sharedSession()  
   let request = NSMutableURLRequest(URL: NSURL(string: "<The address to the login php page>")!)  
   request.HTTPMethod = "POST"  
   request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")  
   request.addValue("application/json", forHTTPHeaderField: "Accept")  
   let postString = "&username=\(username)&password=\(password)"  
   request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)  
   var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in  
     println("Response: \(response)")  
     var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)  
     println("Body: \(dataString)")  
     var err: NSError?  
     var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary  
     // checking whether JSONObjectWithData constructor return an error?   
     if(err != nil) {  
       println(err!.localizedDescription)  
       let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)  
       println("Error could not parse JSON: '\(jsonString)'")  
     }  
     else {  
       // checking for value in the response json  
       if let parseJSON = json {  
         // retrieving the parsed json data for the key 'success'  
         var success = parseJSON["success"] as? Int  
         println("Succes: \(success)")  
       }  
       else {  
         // catching the error  
         let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)  
         println("Something went wrong, Error could not parse JSON: \(jsonString)")  
       }  
     }  
   })  
   task.resume()  
 }  

IOS: Using sharedPreferences in swift ios application

     SharedPreferences allow us to store something in the sharedPreferences memory of the device. You could map the stored value with a key. Once you store something in the sharedPreferences using a key, then you could retrieve the value using the same key. Also you could change the stored value if it is necessary. Nowadays most of the applications make use of sharedPreferences to store the app setting and etc.. In this tutorial you're gonna learn how to use sharedPreferences to store and retrieve value in your ios app using swift language.  



*Copy and paste the below code to your swift class file

>The Below code saves the value India for the key MyCountry.
func storeData(){   
  let sharedPref= NSUserDefaults.standardUserDefaults()   
   sharedPref.setValue("India", forKey: "MyCountry")      
  }   


>The Below code retrieves the value of the key MyCountry.
 And it will store the data if it does not exists.
func retrieveData(){  
 let sharedPref = NSUserDefaults.standardUserDefaults()  
   if let country = prefs.stringForKey("MyCountry"){  
     println("The MyCountry has a Country defined: " + country)  
   }else{  
     //Nothing stored in NSUserDefaults yet. Set a value.  
     sharedPref.setValue("India", forKey: "MyCountry")  
   }  
 }  

Friday, 16 October 2015

IOS: Make an http request from the ios device using swift and also receiving a response as a json array from the server-side PHP Mysql

Hi developers, after a long research on the web i had finally ended up without getting an exact answer for my question "How to send request from ios swift to php and receive response as a json array". Anyway after a a lot of hardwork I had figured out how to do it in the simplest way.

First of all in the swift part we have 'request' variable which holds the URL of the respective php page to which we have to send the request; and the variable 'parameter' holds the value that has to be send to the server as a parameter. The 'nudges' variable holds the key "products" which is the json encoded array response. With the help of a for loop it extracts the respective value of the keys: item1, item2 and item3, and then prints it!

Secondly, we have three PHP web pages to manage the server-side, namely 'db_config.php' which holds database information, 'db_connect.php' which connects to the database and finally 'ios_get_all_items.php' which receives the request parameter from the device and performs MYSQL select operation and then returns the corresponding result in the form of a json array.


Swift:
func fetchData() {   
    var parameter = "AllItems"  
    var session = NSURLSession.sharedSession()   
    let request = NSMutableURLRequest(URL: NSURL(string: "http://mySampleWeb.com/ios_get_all_items.php")!)   
    request.HTTPMethod = "POST"   
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")   
    request.addValue("application/json", forHTTPHeaderField: "Accept")   
    let postString = "&category=\(parameter)"   
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)   
    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in   
    // println("Response: \(response)")   
     var dataStr= NSString(data: data, encoding: NSUTF8StringEncoding)   
    // println("Body: \(dataStr)")   
     var err: NSError?   
     var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary   
     // printing the consol log if the JSONObjectWithData constructor return an error;   
     if(err != nil) {   
      println(err!.localizedDescription)   
      let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)   
      println("Error could not parse the response JSON: '\(jsonString)'")   
     }   
     else {     
      // checking for data in response json   
      if let parseJSON = json {   
       // Okay, the parsedJSON is here, let's get the value for 'success' out of it   
       var success = parseJSON["success"] as? Int   
       //   println("Succes: \(success)")   
       //   println("myMOB: \(mob)");   
       if(success==1){   
        self.deleteTableProduct();   
        //getting json array   
        let nudgesJSONResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! [String : AnyObject]   
        if let nudges = nudgesJSONResult["products"] as? [[String : String]] {   
         for nudge in nudges {   
 //recieving data : the value changes in every iteration  
          let item1= nudge["item1"]   
          println("Got item1: \(item1)")   
          let item2= nudge["item2"]   
          println("Got item2: \(item2)")   
          let item3= nudge["item3"]   
          println("Got item3: \(item3)")   
         }   
        }   
        //json array recieving completed   
         println("json array recieving completed  ")   

  }   
       else{   
        println("success failed value =\(success)")   
       }   
  }   
      else {   
       // If error occurs; problems such as server down.   
       let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)   
       println("Something went wrong. Error could not parse JSON: \(jsonString)")   
      }   
     }   
    })   
    task.resume()   
   }   



PHP:

*db_connect.php
 <?php  
 /*  
 we are connecting to the database using the information in db_config.php file  
 */  
 class DB_CONNECT {  
   function __construct() {  
     $this->connect();  
   }  
   function __destruct() {  
     $this->close();  
   }  
   function connect() {  
     require_once __DIR__ . '/db_config.php';  
     $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());  
     $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());  
     return $con;  
   }  
   function close() {  
     mysql_close();  
   }  
 }  
 ?>  

* db_config.php
 <?php  
 /*  
  * All database connection details  
  */  
 define('DB_USER', "root"); // your database username  
 define('DB_PASSWORD', "root"); // your database password  
 define('DB_DATABASE', "mydb"); // your database name  
 define('DB_SERVER', "localhost"); // your database server  
 ?>  


* ios_get_all_items.php
<?php 
/*  
  * Following code will list all the products  
  */  
 // array for JSON response  
 $response = array();  
 // include db connect class  
 require_once __DIR__ . '/db_connect.php';  
 // connecting to db  
 $db = new DB_CONNECT();  
 if(isset($_POST['category']))  
 {  
 $category= $_POST['category'];  
 }  
 // get all products from products table  
 $result = mysql_query("SELECT * FROM ITEMS where category='$category'") or die(mysql_error());  
 // check for empty result  
 if (mysql_num_rows($result) > 0) {  
   // looping through all results  
   // products node  
   $response["products"] = array();  
   while ($row = mysql_fetch_array($result)) {  
     // temp user array  
     $product = array();  
     $product["item1"] = $row["item1"];  
     $product["item2"] = $row["item2"];  
     $product["item3"] = $row["item3"];  
     // push single product into final response array  
     array_push($response["products"], $product);  
   }  
   // success  
   $response["success"] = 1;  
   // echoing JSON response  
   echo json_encode($response);  
 } else {  
   // no products found  
   $response["success"] = 0;  
   $response["message"] = "No products found";  
   // echo no users JSON  
   echo json_encode($response);  
 }  
 ?>  

Hope you enjoyed it! Don't forget to share the knowledge.