2016년 9월 15일 목요일

Camera & PhotoLibrary 접근 @@ in Swift2.x - Xcode 7.3 iOS 9.3


카메라와 카메라롤, 포토라이브러리 접근하는 메소드
- UImagePickerControllerSourceType.Camera : 카메라
. SourceType 속성을 통해 미디어 소스 형태 설정
- UImagePickerControllerSourceType.SavedPhotoAlbum : 포토앨범 사진 저장 
- UImagePickerControllerSourceType.PhotoLibrary : 사진 



func PhotoLibraryOpen (){
  let picker = UIImagePickerController()
  //editing 여부 (사진 편집)
  picker.allowsEditing = true
  picker.delegate = self
  //타입 선언 Camera save Photo Album, PhotoLibrary
  picker.sourceType = .PhotoLibrary
  presentViewController(picker, animated: true, completion: nil)
}



라이브러리 실행 시 가져오는 이미지 타입
- info[UIImagePickerControllerOriginalImage] as UIImage편집되지 않았거나 촬영된 원본 사진은 다음과 같은 방법으로 info 딕셔너리에서 가져오기
- info[UIImagePickerControllerEditedImage] as UIImage편집된 사진 가져오기

@IBOutlet weak var MyImageSet: UIImageView!
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
  var newImage: UIImage
  if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
    newImage = possibleImage
    print("EditPhotos")
  } else if 
let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
    newImage = possibleImage
    print("OriginalPhotos")
  } else {
    print("null")
    return
  }
  MyImageSet.contentMode = .ScaleAspectFit
  MyImageSet.image = newImage
  dismissViewControllerAnimated(true, completion: nil)
}

   
라이브러리 View 닫기

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
  dismissViewControllerAnimated(true, completion: nil)
}

2016년 9월 14일 수요일

UICollectionView Cell checkbox 이슈 해결 @@ in Swift2.x - Xcode 7.3 iOS 9.3

이어서 지난 번 CheckBox 코딩의 이슈를 해결코자 한다.
[이슈 내용]
1. 선택된 체크박스가 중복되어 나타난다, 즉 아래로 스크롤 시 체크하지 않았던 체크박스도 체크가 된 상태로 나타나는 경우

2. 스크롤 후 다시 원위치 시 체크박스된 박스가 위치가 바뀌는 현상

일단 두가지 이슈의 공통점은 버튼마다 특정 값을 가지고 있지 않다는 것이다.
다시말해 몇번째 Cell의 Checkbox인지 확인이 어렵다는것이다.

그래서 CheckBox 클래스 값에 변수를 만들어 그 변수에
Cell의  indexPath.row 값을 넣기로 했다
------------------------------------------------------------------------------------------
class CheckBox: UIButton {
    // Images
    
    let checkedImage = UIImage(named: "photoSelect_active")! as UIImage
    let uncheckedImage = UIImage(named: "photoSelect_deactive")! as UIImage

    var tagCount: Int = 0
==========================================================================

------------------------------------------------------------------------------------------
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! AlbumPhotoCollectionViewCell
       
        ...
          cell.checkBoxbutton.tagCount = indexPath.row
          
          ...
        return cell

    }
==========================================================================

이렇게 하면 일단 버튼 마다 특정 값을 가지게 할 수 있다.
하지만 이슈처리하는데 가장 풀리지 않았던 문제는 CheckBox 의 중복 되는 문제
하여 CheckBox 클래스 안에서 특정 값을 이용해 Check 표시를 하는 메소드를 만들어보기로 했다.
이렇게 하게 된 가장 큰 이유는 CollectionView 에서 Cell 이 화면에 나타날때마다 객체를 새로 생성
하게 됨을 알게 되었고 생성 될때마다 실행하는 함수를 넣게 될 경우 중복되는 문제를
해결 할 수 있을거라 생각 하였기 때문이였다

일단 tagCount 라는 변수를 이용해 Check 여부를 확인 하는 메소드를 CheckBox 클래스 안에 만들다
------------------------------------------------------------------------------------------
func checkdconform(){
        if GridPhotosHelper.collectionViewCellDic[tagCount] == nil {
            self.isChecked = false
        }else{
           self.isChecked = true
        }
    }
==========================================================================

GridPhotosHelper.collectionViewCellDic[tagCount] 이 값은 체크박스 클릭 시 
tagCount를 key 값으로 딕셔너리로 저장하도록 선언 해놓은 변수이다.
------------------------------------------------------------------------------------------

public struct GridPhotosHelper {

 static var collectionViewCellDic : Dictionary = [Int : Bool]()
...
}
==========================================================================

CheckBox 클래스 내 버튼 클릭 함수에 true, false 값에 따라 딕셔너리로 저장하거나 삭제하도록 코딩을 추가 해준다
------------------------------------------------------------------------------------------
 func buttonClicked(sender:UIButton) {
        print(tagCount)
        if(sender == self){
            if isChecked == true{
                isChecked = false
                GridPhotosHelper.collectionViewCellDic[tagCount] = nil   
            }else{
                isChecked = true
                GridPhotosHelper.collectionViewCellDic[tagCount] = true
            }
        }
    }
==========================================================================
끝으로 객체가 생성 될때마다 위 함수를 실행하도록 코딩을 추가한다
------------------------------------------------------------------------------------------
 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! AlbumPhotoCollectionViewCell
        
        
          cell.checkBoxbutton.tagCount = indexPath.row
          cell.checkBoxbutton.checkdconform()
          
     ...
        return cell

    }
==========================================================================

앱을 테스트 해보면 이슈들이 해결된것을 확인 할 수 있고 체크된 Checkbox 의  값들도
딕셔너리에 따로 저장된다.

2016년 9월 13일 화요일

UICollectionView Cell checkbox 사용 @@ in Swift2.x - Xcode 7.3 iOS 9.3

오늘은 UICollectionView Cell 마다 Checkbox 기능을 추가 할 예정이다.
일단 Checkbox를 넣는 이유는 Poster라이브러리에서 자신이 선택하고 싶은 사진들을 표시하기
위해서이다.

내가 가지고 있는 교재에선 참고할만한 예제가 없어 구글링을 하여 코딩했다.

무슨 이유인지 아직 모르지만 아래코딩은 Checkbox가 중복체크가 된다.(첫 화면에 Checkbox를 체크 하고 스크롤 하여 아래로 내리면 체크하지 않았던 Checkbox에 체크 표시가되어있는 문제가 발생)

그래도 일단 코딩을 정리하고 이슈를 해결 할 예정이다.
----------------------------------------------------------------------------------------------
class CheckBox: UIButton {
    // Images
    
    let checkedImage = UIImage(named: "photoSelect_active.png")! as UIImage
    let uncheckedImage = UIImage(named: "photoSelect_deactive.png")! as UIImage
    
    // Bool property
    var isChecked: Bool = false {
        didSet{
            if isChecked == true {
                self.setImage(checkedImage, forState: .Normal)
            } else if isChecked == false {
                 print("test2!!")
                self.setImage(uncheckedImage, forState: .Normal)
            }
        }
    }
    override func awakeFromNib() {
        self.addTarget(self, action: #selector(CheckBox.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.isChecked = false
    }
    
    func buttonClicked(sender:UIButton) {
        if(sender == self){
            if isChecked == true{
                isChecked = false
               
            }else{
                isChecked = true
               
            }
        }
    }

}
=============================================================================
위 코딩은 구글링을 통해서 체크버튼 클릭 마다 isChecked 값에 따라 이미지를 바꿀수 있도록 한다.
스토리보드 버튼에 위 클래스 값을 넣었다. 참고로 버튼 타입을 "Custom"으로 해주어야만 
이미지가 제대로 나온다.

체크 이미지와 미체크 이미지를 설정 해주고
----------------------------------------------------------------------------------------------
    let checkedImage = UIImage(named: "photoSelect_active")! as UIImage
    let uncheckedImage = UIImage(named: "photoSelect_deactive")! as UIImage
=============================================================================
속성 값에 따른 이미지 배치
----------------------------------------------------------------------------------------------
 // Bool property
    var isChecked: Bool = false {
        didSet{
            if isChecked == true {
                self.setImage(checkedImage, forState: .Normal)
            } else if isChecked == false {
                self.setImage(uncheckedImage, forState: .Normal)
            }
        }
=============================================================================

클래스 시작 시 처음 실행되는 함수 버튼에 터치 함수를 넣어주고 버튼의 속성값을 false 로 설정
----------------------------------------------------------------------------------------------
 // Bool property
override func awakeFromNib() {
        self.addTarget(self, action: #selector(CheckBox.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.isChecked = false
    }
=============================================================================
체크버튼에 들어간 클릭 함수, 클릭마다 속성이 바뀐다
----------------------------------------------------------------------------------------------
 func buttonClicked(sender:UIButton) {
        if(sender == self){
            if isChecked == true{
                isChecked = false
            }else{
                isChecked = true
            }
        }
    }
=============================================================================
스토리보드의 버튼의 클래스 값에 적용 후 테스트를 해보면 
체크버튼이 클릭 될때마다 이미지가 바뀌는것을 확인 할 수 있으나 이슈가 발생한다.

[이슈 정리]
1. 선택된 체크박스가 중복되어 나타난다, 즉 아래로 스크롤 시 체크하지 않았던 체크박스도 체크가 된 상태로 나타나는 경우

2. 스크롤 후 다시 원위치 시 체크박스된 박스가 위치가 바뀌는 현상



2016년 9월 12일 월요일

메모리 체크 ( instruments memory) @@ in Swift2.x - Xcode 7.3 iOS 9.3

지난번 앱 이슈를 확인하기 위해 메모리체크를 하였다.
메모리체크하는 방법을 정리 해볼까 한다.

1.xcode  프로젝트 빌드  후 디버깅 탭 선택
* 빌드를 하지 않았을 경우 아래처럼 디버깅 탭을 눌러도 아무것도 없음 “ No Debug Session” 만 뜸




2. 디버깅 탭에서 Memory 를 선택 하면 우측 화면에 Memory 상태를 나타내는 화면이 뜸
   우측 사단의 Profile in Instruments 클릭


3. Profile in Instruments 을 클릭 한 후 메세지 창이 아래처럼 뜸
   그럼 “Restart” 버튼을 클릭
*Transfer를 클릭 해도 되지만 어떤사람이 저걸 눌렀다가 데이터가 손실되는 일이 발생하였다함




4. 제대로 했다면 앱이 실행되면서 Instruments 가 실행 되면 필터 창에 앱 이름 서치 아래그림 참조
*우측 하단을 보면 옵션설정이 있으나 나중에 블로그참조!! (http://blog.canapio.com/44 여기참조)



5. 이제 메모리 상태가 나온다





6. 그 외 에도 앱 상태를 확인 할 수 있는 방법이 여러가지이다
자세히 알아보려면 구글링하도록 하자!!
오른쪽 상단의 "+" 를 누르면 여러가지 아이콘이 나오는데 한번씩 보면 좋을듯 하다.

2016년 9월 10일 토요일

in-app purchases (Restore 추가) @@ in Swift2.x - Xcode 7.3 iOS 9.3

in-app purchases 적용하기 

앱 내 결제기능을 적용하기위해  in-app purchases를 사용한다.

필요조건
 -  itunes connect 계정 (은행정보 입력되어 있어야 함)


1. 프레임 워크 추가하기

프레임워크는 좌측 프로젝트 > TARGETS > Capabilities > in-App Purchase  ON 으로 하여 완료되었을경우  자동으로 추가됨 




프레임워크 추가 되었는지 확인
프로젝트  > General 하단에 > Libraries > StoreKit.framework 확인

2. 인 앱 제픔 productID 확인하기

 ViewController.swift 

// StoreKit 를 import 해주고 SKProductsRequestDelegate,SKPaymentTransactionObserver 를 추가 합니다
import UIKit
import StoreKit 



class ViewController: UIViewController,SKProductsRequestDelegate,SKPaymentTransactionObserver {
         ...
    }

// productID 에는 itunes connect > 나의 App > CustomApp > App내 추가기능 에 등록 한 제품 ID를 입력 합니다. ( 미리 제품을 등록해야 합니다!)
    

UIViewController,SKProductsRequestDelegate,SKPaymentTransactionObserver {

    // 제품 타이틀과 정보, 구매버튼 아울렛
    @IBOutlet weak var productTitle: UILabel!
    @IBOutlet weak var productDescription: UITextView!
    @IBOutlet weak var buybutton: UIButton!
    @IBOutlet weak var reStorebutton: UIButton!
         var product: SKProduct?


         var productID = "product ID 입력"
                   ...
    }




3. 코딩 작업

이제 결제 작업을 위해 트랜젝션 감시자 설정과, 제품정보를 얻어서 사용자에게 표시하는 메서드
를 만들어야 한다. 

  override func viewDidLoad() {
        super.viewDidLoad()
       //구매제품정보 얻을때까지 구매버튼, Restore 버튼 비활성화

        buybutton.enabled = false
        reStorebutton.enabled = false 
       //결제 작업을 위해 트랜잭션 감시자를 설정
        SKPaymentQueue.defaultQueue().addTransactionObserver(self)
       //앱스토어에 접속하고 지정한 ID에 대한 제품 정보를 가지고 와서 표시하는 함수 호출
        ItemProduct()
}
  // 제품정보가져오는 함수
  func ItemProduct(){
   if SKPaymentQueue.canMakePayments(){
   let request = SKProductsRequest(productIdentifiers: NSSet(object: self.productID) as! Set<String>)
            request.delegate = self

           // 제품정보를 가져올 경우 didReceiveResponse 델리게이트 메서드 호출
            request.start()
        }else{
            print("Please enable in App purchase in Settings")
        }
    }


  //didReceiveResponse 델리게이트 메서드
 func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
        var products = response.products
        print(products)
        if (products.count != 0){
            product = products[0] as SKProduct
            //제품정보 확인! 구매버튼, Restore 버튼 활성화
            buybutton.enabled = true
            reStorebutton. enabled = true        
            // 제품 타이틀과 정보 각각 넣기
            productTitle.text = product!.localizedTitle
            productDescription.text = product!.localizedDescription
        }else{
            print("product not found")
        }
        if response.invalidProductIdentifiers.count != 0 {
            print(response.invalidProductIdentifiers.description)
        }
        for product in products
        {
            print("Product not found: \(product)")
        }   
    }
  // 구매버튼의 함수에 결제프로세스를 시작, 트랜잭션 감시자 객체의 updatedTransactions 메서드를 호출하도록 한다

   @IBAction func buyproduct(sender: AnyObject) { 
        let payment = SKPayment(product: product!)
        SKPaymentQueue.defaultQueue().addPayment(payment)
    }   
// Restore 버튼 함수에 Restore 트랜젝션 메서드 호출
  @IBAction func RestoreAction(sender: AnyObject) {
        print("restore")
        SKPaymentQueue.defaultQueue().addTransactionObserver(self)
        SKPaymentQueue.defaultQueue().restoreCompletedTransactions()

    }


 //updatedTransactions 메서드
    func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transactions in transactions as [SKPaymentTransaction]{
             switch transactions.transactionState{
            case SKPaymentTransactionState.Purchased:
                print("buy, ok unlock")
                self.success()
                SKPaymentQueue.defaultQueue().finishTransaction(transactions)
                break;
            case SKPaymentTransactionState.Failed:
                print("buy error")
                SKPaymentQueue.defaultQueue().finishTransaction(transactions)
                break;
            case SKPaymentTransactionState.Restored:
                print("Rstore")
                self.restoreFeature()
                SKPaymentQueue.defaultQueue().finishTransaction(transactions)
                break;
            default:
                print("defult")
                break;
            }
        }
    }
    
  // 결제 완료 됐을 시 실행될 함수
  func success() {
        buybutton.enabled = false
        print("ok")
    }
  // Restore 완료 됐을 시 실행될 함수
  func restoreFeature(){
        reStorebutton.enabled = false
        print("restore")

    }


이렇게 구매버튼 과 Restore 버튼을 사용하여 인 앱 결제를 마무리 하였다.

2016년 9월 7일 수요일

UITableView delegate 사용 @@ in Swift2.x - Xcode 7.3 iOS 9.3




UIViewController에 UITableView의 델리게이트패턴을 사용하는 방법


UITableViewDataSource, UITableViewDelegate 추가해준다.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate


스토리보드에서 UITableView를 끌어 아울렛을 만들거나 아니면

@IBOutlet var tableView: UITableView!


뷰를 코드로 만들어줘도 상관 없다

let tableView: UITableView = UITableView(frame: CGRect(x: 10, y: 50, width: 200, height:600), style: UITableViewStyle.Plain)


테이블에 나타낼 데이터를 만들고

let Datalist = ["1", "2", "3", "4"]


viewDidLoad() 에 tableView.delegate = self, tableView.dataSource = self 코딩하면

override func viewDidLoad() {
  super.viewDidLoad()
  tableView.delegate = self
  tableView.dataSource = self
}



UITableViewDelegate 메소드를 사용할 수 있게 된다

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
  return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return Datalist.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath:indexPath)
  let row = indexPath.row
  cell.textLabel?.text = Datalist[row]
  return cell

}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  tableView.deselectRowAtIndexPath(indexPath, animated: true)
  let row = indexPath.row
  print(Datalist[row])
}


2016년 9월 5일 월요일

dispatch_async 비동기 처리 @@ in Swift2.x - Xcode 7.3 iOS 9.3

1. 동기와 비동기 개념

  - 동기

  동기 (Synchronize) 방식이란 주어진 명령을 차례대로 처리하되 하나의 업무가 완료될 때 까지는 다음 업무로 넘어가지 않는 방식을 말한다

  - 비동기

  비동기 방식이란 주어진 명령을 차례대로 처리하되 시간이 걸리는 업무는 진행해둔 채로 기다리는 동안 다른 업무를 처리하는 방식입니다.

  - 장단점

  동기 방식은 일관 적인 업무 흐름을 보장 받을 수 있고 동시다발 적 업무가 발생하지 않으므로 이를 제어하기 위한 대응이 불필요, 업무 구성이 단순 해지는 장점을 가지고 있으나 업무를 차례대로 진행하기 때문에 대기 시간이 생기게 되고 시간을 효율적으로 사용하지 못한다는 단점이 있습니다.
비동기 방식은 대기 시간을 줄여줄 수 있으므로 효율적이지만 업무의 구성이 복잡해지기 때문에 일괄적인업무 흐름이 깨지고 이를 제어하기 위한 대응이 필요합니다.

2. 비동기 구현 방식

  iOS Swift에서는 비동기 실행 함수 dispatch_async()를 제공하여 개발자가 내부적으로 프로세스나 스레드에 직접 접근하지 않고도 비동기 방식으로 처리를 할 수 있도록 지원합니다.
글로벌 범위에서 사용할 수 있는 이 함수는 블록(Block)과 GCD를 이용하는데, 이중 GCD는 애플에서 개발한 기술로서 병렬처리와 스레드 풀에 기반을 둔 비동기 방식을 구현해줍니다

3. 구현방식 정리(GCD) 


Serial Dispatch Queue

- FIFO 방식으로 Queue에 대기하는 작업을 순차적으로 처리하는 방식이다. 하나의 작업이 Thread에 의해 실행중이면 다른 작업은 Queue 내부에서 대기하고 있다.

Concurrent Dispatch Queue
- 간단하게 생각하면 큐에 들어오는 작업을 동시적으로 별도의 Thread에서 처리하는 방식이다. 실행되는 Thread의 개수는 시스템 상태에 따라 달라지며, OS에서 알아서 관리해준다.

// 새로운 시리얼 디스패치 큐를 생성한다
dispatch_queue_t serialQueue = dispatch_queue_create("SerialQueue", DISPATCH_QUEUE_SERIAL);

// 새로운 콘커런트 디스패치 큐를 생성한다
dispatch_queue_t concurrentQueue = dispatch_queue_create("ConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);


// 메인 디스패치 큐를 얻어온다
dispatch_queue_t mainQueue = dispatch_get_main_queue();

// 글로벌 디스패치 큐를 얻어온다
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);



출처 : http://ycsycs.tistory.com/3
출처 : [iOS] GCD를 활용한 이미지 비동기 처리하기 |작성자 zzozzo




dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
대해서만 알아보려 한다

출처 : http://seorenn.blogspot.kr/2014/06/swift-gcdgrand-central-dispatch.html

큐는 여러 종류가 있다. 그 중에 필수적으로 알아둬야 할 큐는 글로벌 큐(Global Queue)와 메인 큐(Main Queue) 이다.
dispatch_get_global_queue() 는 GCD에서 쓰는 큐를 가져오는 함수 중 하나이다. 특히 여기서는 글로벌 큐(Global Queue) 라는걸 가져오기 위한 용도이다. 글로벌큐는 백그라운드로 돌아가는 스레드로 UI와는 별도로 동작한다.
글로벌큐는 큐 중에서도 특이점이 있는데, 글로벌 큐는 작업이 들어오면 즉시 스레드를 생성해서 처리한다. 들어오는 만큼 작업을 무한대로 멀티스레딩 한다는 의미이다. 하지만 다른 큐들은 한 번에 하나씩만 작업을 처리한다.

<예제 코드>

let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { 
 // do some task 
 dispatch_async(dispatch_get_main_queue()) { 
  // update some UI 
 } 
}
위 코드를 간단히 설명하자면 global queue에서 작업을 수행하고 main queue에서 UI 변경 작업을 하도록 한 코드다.

추천 게시물

애플 개발자 등록방법 2016년 5월 8일 기준!!

애플 개발자 등록 절차 1. 개발자 등록 페이지 이동    애플 개발자 로그인 > Account 페이지 이동 > 하단 영역 클릭 (이미지 참조)   >> Enroll 클릭 >> 무조건 승인!! ...