2016년 9월 17일 토요일

애드몹 AdMob Swift 화면 하단에 적용 @@ in Swift2.x - Xcode 7.3 iOS 9.3

애드몹 적용하기


import UIKit
import GoogleMobileAds

class ViewController: UIViewController, GADBannerViewDelegate {

  override func viewDidLoad() {
  super.viewDidLoad()

  let bannerView: GADBannerView = GADBannerView(adSize: kGADAdSizeBanner)
  bannerView.frame.origin = CGPointMake(0, self.view.frame.size.height -bannerView.frame.height - 49)
 bannerView.frame.size = CGSizeMake(self.view.frame.width, bannerView.frame.height)

 bannerView.adUnitID = "ca-app-pub-xxxxxxxxxxx/xxxxxxxxx"
 bannerView.delegate = self
 bannerView.rootViewController = self
 let gadRequest:GADRequest = GADRequest()

 // 테스트
 gadRequest.testDevices = [kGADSimulatorID]

 bannerView.loadRequest(gadRequest)
 self.view.addSubview(bannerView)
 }
}

2016년 9월 16일 금요일

Swift 기본 문법 정리 @@ in Swift2.x


Swift 문법 정리

대소문자 구분
let A = 30
let a = 30
이 두 변수는 완전히 서로 다른 변수 이다.

변수
변수는 값을 변경 가능하고 var를 이용해 선언한다.
var i = 1
선언 시 타입을 선언 할 수도 있고
var i : Float = 1.1
var str = "Swift"
대입하는 값으로 타입 선언을 생략할 수 있다
str = "Swift"

상수
상수는 let 으로 선언하고, 한 번 대입된 값을 변경할 수 없다.
let abc = 123
let str = "문자열"

* 변수와 상수명은 [+, _, *, /]와 공백, 첫번째자리에 숫자가 있으면 사용할 수 없고
스위프트에서 사용하는 예약어나 키워드는 변수명으로 사용할수 없습니다.


데이터 타입
-Bool  :  true/false 두가지 종류의 값만 가질 수 있는 자료형으로 논리값 저장시 사용
-Character : 한개 문자 저장
-Int : 양수부터 음수까지의 정수
-Uint(Int8, Int16, Int32, Int64) : Unsigned Integer 줄인 단어로 부호없는 정수 (0 포함)
-Float&Double : 둘다 실수형 값 저장, Float 형은 소수점 아래 7~8 까지 Double 형은 15~16까지
-String : 문자열 저장

문자와 문자열
//문자
let char : character = "a"

//문자열
var str = "abcd"
let str2 = "Swift"

타입이 서로 다른 변수의 결합
String(문자열로 바꾸고 싶은 숫자)

Int(정수로 바꾸고 싶은 문자열)
*숫자로 구성된 문자열만 ex)"123", "345" 등..

배열
// 변경가능
var intArray : [Int] = [ 1, 2, 3, 4, 5 ]

// 변경 불가
let strArray = [ "A", "B", "C" ]

// 개수
intArray.count

// 항목 접근
intArray[2]


딕셔너리
var dic1 : [String:Int] = [ "1월":1, "2월":2, "3월":3]
var dic2 : = ["1월":"January", "2월":"February", "3월":"March" ]
//접근
dic1["2월"]

세미콜론(;)
스위프트 경우 사용하거나 안하거나 상관없다.

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년 5월 8일 기준!!

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