2016年3月17日 星期四

swift send value via HTTPHeader

i.e authentication

http://stackoverflow.com/questions/35071753/send-data-through-params-to-rails-app-from-ios-in-swift


request.setValue("XXXXXXXXXX", forHTTPHeaderField: "Authorization")

func postRequest2(x: String) {
    let string = "http://localhost:3000/api/users/2/products"
    let url = NSURL(string: string)
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: url!)
    let params = ["title": "Fifth Title"]
    request.setValue("XXXXXXXXXX", forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.HTTPMethod = "POST"
    do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
    }
    catch {

    }
    let tache = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
        if let antwort = response as? NSHTTPURLResponse {
            let code = antwort.statusCode
            print(code)
        }
    }
    tache.resume()

}

swift - A Simple Table View Example

https://medium.com/@ronm333/a-simple-table-view-example-in-swift-cbf9a405f975#.egj26mr64

Swift waitUntilAllTasksAreFinished error


http://stackoverflow.com/questions/26947608/waituntilalltasksarefinished-error-swift

func checkLogin(succeed: Bool, msg: String) {
    if (succeed) {

        NSOperationQueue.mainQueue().addOperationWithBlock {
            self.performSegueWithIdentifier("logInTrue", sender: self)
        }        
    }
}

swift - NSUserDefaults

https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-nsuserdefaults


let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(25, forKey: "Age")
defaults.setBool(true, forKey: "UseTouchID")
defaults.setDouble(M_PI, forKey: "Pi")

defaults.setObject("Paul Hudson", forKey: "Name")
defaults.setObject(NSDate(), forKey: "LastRun")
When you set values like that, they become permanent – you can quit the app then re-launch and they'll still be there, so it's the ideal way to store app configuration data.
As mentioned, you can use NSUserDefaults to store arrays and dictionaries, like this:
let array = ["Hello", "World"]
defaults.setObject(array, forKey: "SavedArray")

let dict = ["Name": "Paul", "Country": "UK"]
defaults.setObject(dict, forKey: "SavedDict")
When it comes to reading data back, it's still easy but has an important proviso: NSUserDefaults will return a default value if the setting can't be found. You need to know what these default values are so that you don't confuse them with real values that you set. Here they are:
  • integerForKey() returns an integer if the key existed, or 0 if not.
  • boolForKey() returns a boolean if the key existed, or false if not.
  • floatForKey() returns a float if the key existed, or 0.0 if not.
  • doubleForKey() returns a double if the key existed, or 0.0 if not.
  • objectForKey() returns AnyObject? so you need to conditionally typecast it to your data type.
With that in mind, you can read values back like this:
let defaults = NSUserDefaults.standardUserDefaults()

let age = defaults.integerForKey("Age")
let useTouchID = defaults.boolForKey("UseTouchID")
let pi = defaults.doubleForKey("Pi")
When retrieving objects, the result is optional. This means you can either accept the optionality, or typecast it to a non-optional type and use the nil coalescing operator to handle missing values. For example:
let array = defaults.objectForKey("SavedArray") as? [String] ?? [String]()

rails api docs

important one :

http://apionrails.icalialabs.com/book/chapter_one

its github
https://github.com/kurenn/market_place_api


User Authentication on iOS with Ruby on Rails and Swift



github





some blogs

http://www.yoniweisbrod.com/rails-api-mini-guide/

https://labs.kollegorna.se/blog/2015/04/build-an-api-now/

http://www.andrewhavens.com/posts/20/beginners-guide-to-creating-a-rest-api/

https://codedecoder.wordpress.com/2013/02/21/sample-rest-api-example-in-rails/


2016年3月4日 星期五

api problem Stub Method error in request spec

according to the tutorial
http://apionrails.icalialabs.com/book/chapter_five

to setting current_user will face a problem


Failure/Error: authentication.stub(:request).and_return(request)



http://stackoverflow.com/questions/26428882/stub-method-error-in-request-spec


require 'rails_helper'

class Authentication
  include Authenticable
end

describe Authenticable, :type => :controller do
  let(:authentication) { Authentication.new }

  describe "#current_user" do
    before do
      @user = FactoryGirl.create :user
      request.headers["Authorization"] = @user.auth_token
      allow(authentication).to receive(:request).and_return(request)
    end

    it "returns the user from the authorization header" do
      expect(authentication.current_user.auth_token).to eql @user.auth_token
    end
  end
end
app/controllers/concerns/authenticable.rb
module Authenticable
  # Devise methods overwrites
  def current_user
    @current_user ||= User.find_by(auth_token: request.headers['Authorization'])
  end

  def request
    request
  end
end

2016年3月1日 星期二

iOS Swift Barcode Reading

http://shrikar.com/implementing-barcode-scanning-in-ios8-with-swift/

http://www.appcoda.com/qr-code-reader-swift/

https://www.hackingwithswift.com/example-code/media/how-to-scan-a-barcode


http://stackoverflow.com/questions/31170750/ios-swift-barcode-reading


import UIKit
import AVFoundation


class BarCodeViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

    let session         : AVCaptureSession = AVCaptureSession()
    var previewLayer    : AVCaptureVideoPreviewLayer!
    @IBOutlet weak var highlightView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Allow the view to resize freely
//        self.highlightView.autoresizingMask =   UIViewAutoresizing.FlexibleTopMargin |
//            UIViewAutoresizing.FlexibleBottomMargin |
//            UIViewAutoresizing.FlexibleLeftMargin |
//            UIViewAutoresizing.FlexibleRightMargin
//        
        // Select the color you want for the completed scan reticle
        self.highlightView.layer.borderColor = UIColor.greenColor().CGColor
        self.highlightView.layer.borderWidth = 3

        // Add it to our controller's view as a subview.
        self.view.addSubview(self.highlightView)


        // For the sake of discussion this is the camera
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

        // Create a nilable NSError to hand off to the next method.
        // Make sure to use the "var" keyword and not "let"
        var error : NSError? = nil
        var input: AVCaptureDeviceInput = AVCaptureDeviceInput()
        do {
            input = try  AVCaptureDeviceInput(device: device) as AVCaptureDeviceInput
        } catch let myJSONError {
            print(myJSONError)
        }

        // If our input is not nil then add it to the session, otherwise we're kind of done!
        if input !=  AVCaptureDeviceInput() {
            session.addInput(input)
        }
        else {
            // This is fine for a demo, do something real with this in your app. :)
            print(error)
        }

        let output = AVCaptureMetadataOutput()
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        session.addOutput(output)
        output.metadataObjectTypes = output.availableMetadataObjectTypes


        previewLayer = AVCaptureVideoPreviewLayer(session: session)
        previewLayer.frame = self.view.bounds
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        self.view.layer.addSublayer(previewLayer)

        // Start the scanner. You'll have to end it yourself later.
        session.startRunning()

    }

    // This is called when we find a known barcode type with the camera.
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {

        var highlightViewRect = CGRectZero

        var barCodeObject : AVMetadataObject!

        var detectionString : String!

        let barCodeTypes = [AVMetadataObjectTypeUPCECode,
            AVMetadataObjectTypeCode39Code,
            AVMetadataObjectTypeCode39Mod43Code,
            AVMetadataObjectTypeEAN13Code,
            AVMetadataObjectTypeEAN8Code,
            AVMetadataObjectTypeCode93Code,
            AVMetadataObjectTypeCode128Code,
            AVMetadataObjectTypePDF417Code,
            AVMetadataObjectTypeQRCode,
            AVMetadataObjectTypeAztecCode
        ]


        // The scanner is capable of capturing multiple 2-dimensional barcodes in one scan.
        for metadata in metadataObjects {

            for barcodeType in barCodeTypes {

                if metadata.type == barcodeType {
                    barCodeObject = self.previewLayer.transformedMetadataObjectForMetadataObject(metadata as! AVMetadataMachineReadableCodeObject)

                    highlightViewRect = barCodeObject.bounds

                    detectionString = (metadata as! AVMetadataMachineReadableCodeObject).stringValue

                    self.session.stopRunning()

                    self.alert(detectionString)
                    break
                }

            }
        }

        print(detectionString)
        self.highlightView.frame = highlightViewRect
        self.view.bringSubviewToFront(self.highlightView)

    }



    func alert(Code: String){
        let actionSheet:UIAlertController = UIAlertController(title: "Barcode", message: "\(Code)", preferredStyle: UIAlertControllerStyle.Alert)

        // for alert add .Alert instead of .Action Sheet


        // start copy

        let firstAlertAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:


            {
                (alertAction:UIAlertAction!) in


                // action when pressed

                self.session.startRunning()




        })

        actionSheet.addAction(firstAlertAction)

        // end copy






        self.presentViewController(actionSheet, animated: true, completion: nil)

    }



}