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년 9월 4일 일요일

PHImageManager를 이용한 사진이미지 로드 @@ in Swift2.x - Xcode 7.3 iOS 9.3



PHImageManager를 이용한 앨범의 Thumbnail 로 이용할 사진 이미지 불러오기

<참조>
https://developer.apple.com/reference/photos/phimagemanager

앨범 리스트에서 앨범의 Thumbnail 이미지로 사용 될 이미지를 불러오도록 하겠습니다.
PHFetchResult 에 특정앨범의 이미지타입의 파일을 가져와 마지막에 있는 이미지 파일(최근 날짜 이미지)로 가져오도록 한다.

<주요기능을 담당하는 코드>

이미지 파일만 불러오도록 옵션 값 설정
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue)

앨범 정보 가져오기>      
let assetsFetchResult: PHFetchResult = PHAsset.fetchAssetsInAssetCollection(AlbumsResult, options: fetchOptions)

마지막 사진이미지 선택
let imageAsset = assetsFetchResult.lastObject as? PHAsset 

이미지 로드
manager.requestImageForAsset(imageAsset, targetSize: CGSize, contentMode: .AspectFill, options: requestOptions, resultHandler: { (image, info) -> Void in ..


<완성된 코드>
func getThumbnailWithIdentifer(AlbumsResult:PHAssetCollection, groesse: CGSize, completion: (image:UIImage?) -> Void) {
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
  // 앨범 타이틀을 이용해 특정 앨범의 사진들을 가져온다
    let fetchOptions = PHFetchOptions()
    fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue)
    let manager = PHImageManager.defaultManager()
    let assetsFetchResult: PHFetchResult = PHAsset.fetchAssetsInAssetCollection(AlbumsResult, options: fetchOptions)
    if assetsFetchResult.count > 0 {
    // 가져온 사진중 마지막 사진을 선택하고
      if let imageAsset = assetsFetchResult.lastObject as? PHAsset {
      // 불러올 사진의 이미지 옵션값을 넣은 다음
      let requestOptions = PHImageRequestOptions()
      requestOptions.synchronous = false
      requestOptions.deliveryMode = .HighQualityFormat
      //requestImageForAsset 을 이용해 이미지를 불러온다
      manager.requestImageForAsset(imageAsset, targetSize: groesse, contentMode: .AspectFill, options: requestOptions, resultHandler: { (image, info) -> Void in
      completion(image: image)
      })
      } else {
       completion(image: nil)
      }
   } else {
    completion(image: nil)
   }
  }
}



2016년 8월 31일 수요일

PHAssetCollection의 subtype으로 특정 앨범 정보 확인 @@ in Swift2.x - Xcode 7.3 iOS 9.3

특정앨범 정보 로드

앨범 리스트 가져올때 PHAssetCollection 의  subtype 값을 설정함으로써 자신이 원하는 앨범
정보를 가져올 수 있다.

<참조>
let Customalbums = PHAssetCollection.fetchAssetCollectionsWithType(. SmartAlbum, subtype: .Any, options: fetchOptions)

<subtype 정리>
let Customalbums = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
// 사용자가 만든 앨범

let SmartAlbumPanoramas = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumPanoramas, options: fetchOptions)

let SmartAlbumFavorites = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumFavorites, options: fetchOptions)

let SmartAlbumSelfPortraits = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumSelfPortraits, options: fetchOptions)

let SmartAlbumScreenshots = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumScreenshots, options: fetchOptions)

let SmartAlbumBursts = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumBursts, options: fetchOptions)

let SmartAlbumRecentlyAdded = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumRecentlyAdded, options: fetchOptions)

let Cmeraroll = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumUserLibrary, options: fetchOptions)




앨범 값 을 album 이라는 상수에 저장하여 PHAssetCollection 의 localizedTitle 을 이용해 앨범 타이틀 이름 로드

let albumTitle : String = album.localizedTitle!




fetchAssetsInAssetCollection 의 count 을 이용해 앨범 사진 수 로드


let assetsFetchResult: PHFetchResult = PHAsset.fetchAssetsInAssetCollection(album, options: nil)
let albumCount = assetsFetchResult.count



options 값을 설정하여 이미지파일만 가져오기

let fetchOptions2 = PHFetchOptions()
fetchOptions2.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue)



<완성된 예제 코드>


// 앨범리스트 담을 변수 설정
var albumList:[AlbumModel] = [AlbumModel]()
// 옵션 값
let fetchOptions = PHFetchOptions()
//fetchAssetCollectionsWithType의 subtype 타입값을 설정하여 가지고 오고 싶은 앨범만 선택
let Customalbums = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
let SmartAlbumPanoramas = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumPanoramas, options: fetchOptions)
let SmartAlbumFavorites = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumFavorites, options: fetchOptions)
let SmartAlbumSelfPortraits = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumSelfPortraits, options: fetchOptions)
let SmartAlbumScreenshots = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumScreenshots, options: fetchOptions)
let SmartAlbumBursts = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumBursts, options: fetchOptions)
let SmartAlbumRecentlyAdded = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumRecentlyAdded, options: fetchOptions)
let Cmeraroll = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumUserLibrary, options: fetchOptions)
// 각 앨범의 사진 타이틀이름, 수 가져오기
[Cmeraroll, SmartAlbumRecentlyAdded, SmartAlbumSelfPortraits, SmartAlbumFavorites, SmartAlbumBursts, SmartAlbumPanoramas, SmartAlbumScreenshots, Customalbums].forEach {
    $0.enumerateObjectsUsingBlock { collection, index, stop in guard let album = collection as? PHAssetCollection else { return }
    // PHAssetCollection 의 localizedTitle 을 이용해 앨범 타이틀 가져오기
    let albumTitle : String = album.localizedTitle!
    // 이미지만 가져오도록 옵션 설정
    let fetchOptions2 = PHFetchOptions()
    fetchOptions2.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.Image.rawValue)
    let assetsFetchResult: PHFetchResult = PHAsset.fetchAssetsInAssetCollection(album, options: fetchOptions2)
    // PHFetchResult 의 count 을 이용해 앨범 사진 갯수 가져오기
    let albumCount = assetsFetchResult.count
    // 저장
    let newAlbum = AlbumModel(name:albumTitle, count: albumCount, collection:album)
     print(newAlbum.name)
     print(newAlbum.count)

     //앨범 정보 추가
    albumList.append(newAlbum)
    }
  }


  class AlbumModel {
    let name:String
    let count:Int
    let collection:PHAssetCollection
    init(name:String, count:Int, collection:PHAssetCollection) {
    self.name = name
    self.count = count
    self.collection = collection
  }

}

2016년 8월 30일 화요일

fetchAssetsInAssetCollection 으로 앨범 내 사진 수 가져오기 @@ in Swift2.x - Xcode 7.3 iOS 9.3



PHAssetCollection 이용하여 모바일 내 앨범정보를 가져와 타이틀과 사진 장수를 가져오려 했으나
PHAssetCollection 의 메타데이터 estimatedAssetCount 를 사용하면 "9223xx20368xx5807" 메세지가 동일하게 나타나는 문제점이 있었다.

PHAsset 클래스의 fetchAssetsInAssetCollection 을 기존코딩에 추가하여 

사진 장수를 가져오는 해결책을 알아냈다.

fetchAssetsInAssetCollection(_ assetCollection: PHAssetCollection, options options: PHFetchOptions?) -> PHFetchResult


fetchAssetCollections 을 사용해서 PHFetchResult로 값을 가져올 경우 estimatedAssetCount 의 인자값을 출력 시 "9223xx20368xx5807" 메세지가 나오기 때문에 <참조>
let options:PHFetchOptions = PHFetchOptions()
let getAlbums: PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .Any, options: options)
https://developer.apple.com/reference/photos/phfetchresult



result 인자 값으로 count 가 있는fetchAssetsInAssetCollection 사용해 보기로 했다.

func GetAlbums() {
  let options:PHFetchOptions = PHFetchOptions()
  let getAlbums : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .Any, options: options)
  // 앨범 정보
  print(getAlbums)
  for i in 0 ..< getAlbums.count{
    let assetCollection:PHAssetCollection = getAlbums[i] as! PHAssetCollection
    print(assetCollection.localizedTitle)

    print(assetCollection.estimatedAssetCount)
  // 위 글에서 특정앨범의 정보를 가져오는 fetchAssetsInAssetCollection 을 사용한다
  // PHFetchResult의 타입의 상수에 값을 저장한다
  // PHFetchResult 의 result 값에 count 가 있다

    let assetsFetchResult: PHFetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil)
  // 출력 시 기존 생성된 앨범들의 사진 및 비디오 수가 나옴
  print("assetsFetchResult.count=\(assetsFetchResult.count)")
  } 

}


앨범들의 사진 수를  (Count) 를 제대로 가져오는걸 확인 할 수 있다.






2016년 8월 29일 월요일

PHAssetCollection 을 이용한 PhotoLibrary 앨범 정보 로드 @@ in Swift2.x - Xcode 7.3 iOS 9.3


PhotoLibrary 의 앨범 Data Load

*PHAssetCollection.fetchAssetCollectionsWithType 의 파라미터 값 설명참조
let getAlbums : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .Any, options: options)



모바일에 저장된 사진앨범들의 정보(타이틀이름, 이미지파일)를 로드
사진앨범의 타이틀과 사진 수를 가져오는데 PHAssetCollection 사용하였습니다.

func GetAlbums() {
  let options:PHFetchOptions = PHFetchOptions()
  let getAlbums : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: options)
  // 앨범 정보
  print(getAlbums)
  for i in 0 ..< getAlbums.count{
    let collection = getAlbums[i]
    // . localizedTitle = 앨범 타이틀
    let title : String = collection.localizedTitle
      if(collection.estimatedAssetCount != nil){
        // . estimatedAssetCount = 앨범 내 사진 수
        let count : Int = collection.estimatedAssetCount
        print(count)
        print(title)
      }else{
      }
   }
}


위 코딩을 실행하면 자신이 추가한 앨범들의 타이틀과 사진 장수를 확인 할 수 있다
위 코드를 실행하면 앨범들의 타이틀 정보는 제대로 가져오나 사진 수를 가져오는데 
잘못된 값을 가져오는것을 확인 했다.

<앨범 내 사진 수를 가져오는 포스팅은 아래 링크를 참고>
https://swifteyes.blogspot.kr/2016/08/grid-poster-2-phassets-class-2-in.html


*기본 라이브러리 앨범들의 정보를 확인은 .Album -> .SamrtAlbum 으로 수정하면 앨범 타이틀은
출력이 되나 필요없는 앨범 타이틀까지 출력 되며 사진 수가 알 수 없는 숫자들로  "9223xx20368xx5807" 동일하게 나타난다. 



<subtype 을 이용해 자신이 원하는 앨범선택이 가능하다>


case 
albumRegular

An album created in the Photos app.
case albumSyncedEvent
An Event synced to the device from iPhoto.
case albumSyncedFaces
A Faces group synced to the device from iPhoto.
case albumSyncedAlbum
An album synced to the device from iPhoto.
case albumImported
An album imported from a camera or external storage.
case albumMyPhotoStream
The user’s personal iCloud Photo Stream.
case albumCloudShared
An iCloud Shared Photo Stream.
case smartAlbumGeneric
A smart album of no more specific subtype.
case smartAlbumPanoramas
A smart album that groups all panorama photos in the photo library.
case smartAlbumVideos
A smart album that groups all video assets in the photo library.
case smartAlbumFavorites
A smart album that groups all assets that the user has marked as favorites.
case smartAlbumTimelapses
A smart album that groups all time-lapse videos in the photo library.
case smartAlbumAllHidden
A smart album that groups all assets hidden from the Moments view in the Photos app.
case smartAlbumRecentlyAdded
A smart album that groups assets that were recently added to the photo library.
case smartAlbumBursts
A smart album that groups all burst photo sequences in the photo library.
case smartAlbumSlomoVideos
A smart album that groups all Slow-Mo videos in the photo library.
case smartAlbumUserLibrary
A smart album that groups all assets that originate in the user’s own library (as opposed to assets from iCloud Shared Albums).
case smartAlbumSelfPortraits
A smart album that groups all photos and videos captured using the device’s front-facing camera.
case smartAlbumScreenshots
A smart album that groups all images captured using the device’s screenshot function.

case any
A bit mask representing all possible subtypes.



options 파라미터 값을 이용해 앨범에서 이미지 타입의 파일만 가져오기

let options = PHFetchOptions()
// 옵션 값 설정 : 이미지 타입
options.predicate = NSPredicate(format: "mediaType = %d",PHAssetMediaType.Image.rawValue)
options.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: true) ]
let result : PHFetchResult = PHAsset.fetchAssetsWithOptions(options)
  for i in 0 ..< result.count {
    let asset = result[i] as! PHAsset
    print("date = \(asset.creationDate!)")
    print("location = \(asset.location)")
    print("width = \(asset.pixelWidth), height=\(asset.pixelHeight)")
  }

options.predicate 값에 이미지타입의 파일만 가져오도록 할 수 있다.

특정앨범 선택하기

특정 앨범을 선택할땐 아래처럼 format을 title로하여 앨범 이름 값을 넣어주면 된다

let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", named)


<특정 앨범의 정보를 가져오는 내용을 아래 링크를 참조>
https://swifteyes.blogspot.kr/2016/08/grid-poster-3-phassets-class-3-in.html



2016년 7월 22일 금요일

React.js 란? (리액트 소개 )

React 란?

유저 인터페이스를 만들기 위한 라이브러리 


*React 네이티브 : 모바일 네이티브 앱을 리액트로 만들수 있음


정의

React는 페이스북에서 개발한 유저인터페이스 라이브러리로서 개발자로 하여금 재사용 가능한 UI를 생성 할 수 있게 해줍니다. 이 라이브러리는 현재 페이스북, 인스타그램, 야후, 넷플릭스를 포함한 많은 큰 서비스에서 사용되고 있습니다.
이 라이브러리는 Virtual DOM 이라는 개념을 사용하여 상태의 변함에 따라 선택적으로 유저인터페이스를 렌더링합니다.
따라서, 최소한의 DOM 처리로 컴포넌트들을 업데이트 할 수 있게 해줍니다.

핵심

"Virtual Dom" 

//JQuery
$("#content").html("whatever");
//JavaScript
document.getElementById("content").innerHTML = "whatever"

위처럼 "content" div 내용변경 시 실제 DOM을 직접 처리하는것은 성능도 느리고 비효율적이며 관리하기 힘듭니다. 간단한 처리의 경우 상관없지만 처리해야할 데이터가 많을 경우 관리하기 힘들어집니다.
반면, "Virtual Dom" 은 이를 추상화한 시킨것으로 자바스크립트 객체에 불과하며 그안에서 처리하는것은 이미 렌더링된 HTML 을 실제 DOM API 를 사용해서 처리하는것보다 훨씬 빠릅니다.

특징

1. Virtual DOM 을 사용합니다
2. JSX: JSX 는 JavaScript 의 확장 문법입니다. DOM 엘리먼트들을 만들 때 JavaScript 형식으로 작성해야 하는 것을, XML 과 비슷한 형태로 작성할 수 있게 해줍니다. 이를 사용하는것은 권장사항이고 필수는 아닙니다. 하지만 사용하지 않으면 좀 불편합니다.
3. Components React는 모두 Component 에 대한 것 입니다. React 개발을 할 때는 모든 것을 Component 로서 생각해야 합니다. 컴포넌트에 대한 자세한 내용은 앞으로 작성 될 강좌에서 다루겠습니다.


장점

1. "Virtual Dom" 사용
2. 배우기 간단
    : angular.js, ember.js, backbone.js 에서 데이터를 관리하는 controller 나 HTML 조각인 directive 처럼 코드를 분리하지 않고 "Components" 단 하나만 사용
3. 뛰어난 Garbage Collection 메모리관리 와 성능
4. 서버사이드 렌더링(초기구동 딜레이 & 검색엔진 최적화), 클라이언트사이드 렌더링 둘다 지원
5. 매우 간편한 UI 수정 및 재사용
6. 페이스북 개발자가 만들어 지속적인 업데이트 (밀어주고 있음)
7. 다른 프레임워크나 라이브러리와 혼용가능

단점

1. View only  
   : View 즉, 보여지는 부분만 관여하기 때문에 데이트 데이터모델링, 라우팅, AJAX 등의 기능이 없음
2. IE8 이하 지원 X (IE8 이하지원 하는방법 : React 14버전이하 사용)



  

2016년 7월 6일 수요일

"Could not load the "(null)" image referenced from a nib in the bundle with identifier "" 이슈 해결

<이슈>

"Could not load the "(null)" image referenced from a nib in the bundle with identifier "<app bundle>"

<해결>

위 이슈가 발생 하는것은 스토리 보드 의 imageView 이미지 로드 실패하여 나타나는 메세지이다
imageView 삭제 하거나 이미지 이름 확인하여 수정한다

추천 게시물

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

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