Thursday, September 1, 2016

Using NSUserDefaults(sharedPreferences) in ios application





Use NSUserDefaults: - note that this is for small bits of data, such as the current level like you mentioned. Don't abuse this and use it as a large database, because it is loaded into memory every time you open your app, whether you need something from it or not (other parts of your app will also use this).

Objective-C:

Reading:
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];

NSString *currentLevelKey = @"currentlevel";

if ([preferences objectForKey:currentLevelKey] == nil)
{
    //  Doesn't exist.
}
else
{
    //  Get current level
    const NSInteger currentLevel = [preferences integerForKey:currentLevelKey];
}
Writing:
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];

NSString *currentLevelKey = @"currentlevel";

const NSInteger currentLevel = ...;
[preferences setInteger:currentLevel forKey:currentLevelKey];

//  Save to disk
const BOOL didSave = [preferences synchronize];

if (!didSave)
{
    //  Couldn't save (I've never seen this happen in real world testing)
}
.

Swift:

Reading:
let preferences = NSUserDefaults.standardUserDefaults()

let currentLevelKey = "currentLevel"

if preferences.objectForKey(currentLevelKey) == nil {
    //  Doesn't exist
} else {
    let currentLevel = preferences.integerForKey(currentLevelKey) //Integer Value
let currentLevel = preferences.objectForKey(currentLevelKey) as! String            
    let currentLevel = preferences.boolForKey(currentLevelKey)//Boolean value
}
Writing:
let preferences = NSUserDefaults.standardUserDefaults()

let currentLevelKey = "currentLevel"

let currentLevel = ...
preferences.setInteger(currentLevel, forKey: currentLevelKey)
// store string value
preferences.setObject(saveValue, forKey: currentLevelKey)
//
 preferences.setBool(saveValue, forKey: currentLevelKey)
// Save to disk let didSave = preferences.synchronize() if !didSave { // Couldn't save (I've never seen this happen in real world testing) }

Refer

Send a POST Request to a URL using Swift



Swift code that sends HTTP POST request and reads response body:

HTTPHelper.swift:

//  HTTPHelper.swift
//  Created by Samsul Hoque on 8/30/16.
//  Copyright © 2016 Sams . All rights reserved.
//

class HTTPHelper{
class func httpPostDataDic(postURL:NSURL,postString:NSString,completionHandler:(NSDictionary?, NSError?) -> Void ) -> NSURLSessionTask{
    var responseResultData: NSDictionary = NSDictionary()
    let request = NSMutableURLRequest(URL:postURL);
    request.HTTPMethod = "POST";// Compose a query string
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
    print(request)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        if error != nil
        {
            print("error=\(error)")
            completionHandler(nil, error)
            return
        }
       // You can print out response object
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        //            print("responseString = \(responseString)")
        if let responseString = responseString {
            print("responseString = \(responseString)")
        }
        //Let's convert response sent from a server side script to a NSDictionary object:
        do {
            let myJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
            responseResultData=myJSON!
            completionHandler(responseResultData, nil)
        } catch {
            print(error)
        }
    }
    task.resume()
    return task


  }

}

Call this HTTPHelper Post Function :

@IBAction func loginBTN(sender: AnyObject) {

    let myUrl = NSURL(string: "http://www.swiftdeveloperblog.com/http-post-example-script/")
    let postString = "firstName=James&lastName=Bond";

 HTTPHelperDu8.httpPostDataDic(myUrl!, postString: postString) {
        (responseResult, error) -> Void in

        if error != nil{

            print(error)
        }
        else{
            if let resutlData = responseResult{          //To get rid of optional
               print(resutlData)

                //your code

            }

        }



    }
Objective-c:here

Wednesday, August 31, 2016

How to use virtual device (emulator) in android studio.


.## At first run to the AVD Manager :
STEP-1.   select Tools   than Android than AVD Manager button.
STEP-2.  click AVD Manager in the tool bar.
STEP-3. than show the message.


       
STEP-4. click Create Virtual Device.
STEP-5. than show the Select Hardware page.
STEP-6. select hardware profile than click next button.


STEP-7. than show the System Image page.
STEP-8. download Release Name.





STEP-7. click next button
STEP-8. show the Android Virtual Device (AVD) page.




## Finally click Finish button and use Virtual device in Android Studio.

Sunday, August 28, 2016

Allowing HTTP Connections in IOS Apps


Open your Info.plist file, (+) click and select “Add Row”. Type in “App Transport Security Settings” as key and afterwards create a sub-entry with the key “Allow Arbitrary Loads” that has the value “YES”.
Your plist file should look like this:

Saturday, August 27, 2016

pod setup,when staying on “Setting up Cocoapods Master repo”


Running pod command:
pod install 
Try running in verbose mode:
pod install --verbose
This'll show you what cocoapods is up to:
Setting up CocoaPods master repo

Cloning spec repo `master` from `https://github.com/CocoaPods/Specs.git` (branch `master`)
  $ /usr/bin/git clone 'https://github.com/CocoaPods/Specs.git' master
  Cloning into 'master'...
Solve:

Step-1: pod repo remove master
To get a progression, you can clone master yourself:
pod repo remove master



Step-2: download data from git:

git clone https://github.com/CocoaPods/Specs.git ~/.cocoapods/repos/master


Step-3: After complete download ,run pod setup command 

pod setup



Sunday, July 31, 2016

Pinterest SDK integrates in iOS apps




step : 1 Register for a Client ID from here
step : 2 Install the SDK 
The SDK is a cocoapod, so you’ll need a podfile for your app before you begin. To install the SDK:
  1. Open your Podfile and add the following dependency in the target “<your-app>” do section:
    pod “PinterestSDK”, :git => “git@github.com:pinterest/ios-pdk.git”
    
  2. OR
  3. pod "PinterestSDK", :git => "https://github.com/pinterest/ios-pdk.git"
  4. Save your Podfile.
  5. Run pod install from the command line. You've now installed the iOS SDK.


step : 3 Configure Xcode
You’ll need to configure .plist on your project in order to redirect back to your app after authentication. Do this by adding a URL scheme to your .plist.
In Xcode, right-click your .plist and select Open As > Source Code. Copy and paste the following code inside the <dict>...</dict>, replacing {your-app-id} with your App ID.
<key>CFBundleURLTypes</key>
  <array>
    <dict>
      <key>CFBundleURLName</key>
      <string></string>
      <key>CFBundleURLSchemes</key>
      <array>
        <string>pdk{your-app-id}</string>
      </array>
    </dict>
  </array>

step : 4 Configure the PDK Client

Finally, you’ll need to link your App ID to the PDK Client in your app.

[PDKClient configureSharedInstanceWithAppId:@"12345"];

step : 5 To use the Pinterest framework you will need to import it into your file.
 #import "PDKPin.h"

step : 6 To use the standard PinIt Button in a view add it as so:

UIButton *pinItButton = [UIButton buttonWithType:UIButtonTypeSystem];
pinItButton.translatesAutoresizingMaskIntoConstraints = NO;
[pinItButton setTitle:NSLocalizedString(@"PinIt", nil) forState:UIControlStateNormal];
[pinItButton addTarget:self action:@selector(pinItButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:pinItButton];
step : 7 You will need to handle the action an example of this is below:

- (void)pinItButtonTapped:(UIButton *)button
  {

  [PDKPin pinWithImageURL:[NSURL URLWithString:@"http://placekitten.com/500/400"]
                   link:[NSURL URLWithString:@"https://www.pinterest.com"]
     suggestedBoardName:@"ABC-XYZ"
                   note:@"The Pinterest Logo"
            withSuccess:^
 {
     NSLog(@"successfully pinned pin");

 }
             andFailure:^(NSError *error)
 {
            NSLog(@"pin it failed");

 }];
}

Note : If plist file was missing the BundleDisplayName. In order to solve this problem you just need to add it to the plist file.

<key>CFBundleDisplayName</key>
<string>${PRODUCT_NAME}</string>



 

Copyright @ 2014 Tech Tutorial .