Showing posts with label ios. Show all posts

iBeacon 和 BLE 的差異

1. Use Core Location framework to find iBeacon's distance.

使用CLLocationManagerDelegate  抓取Beacon 和裝置間的距離
// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager
        didRangeBeacons:(NSArray *)beacons
               inRegion:(CLBeaconRegion *)region {
 
   if ([beacons count] > 0) {
      CLBeacon *nearestExhibit = [beacons firstObject];
 
      // Present the exhibit-specific UI only when
      // the user is relatively close to the exhibit.
      if (CLProximityNear == nearestExhibit.proximity) {
         [self presentExhibitInfoWithMajorValue:nearestExhibit.major.integerValue];
      } else {
         [self dismissExhibitInfo];
   }
}

https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/LocationAwarenessPG/RegionMonitoring/RegionMonitoring.html

2. Use Core Bluetooth framework to communicate with BLE device.

在架構中有分Centrals(手機端) 和 Peripherals(裝置端) , Centrals 由CBCentralManager 這個物件來管理和Peripherals連線的事宜. 而裝置端則是 CBPeripheral  . CBPeripheral 下會有 CBService  代表不同的服務.
以上使用時需用到 CBCentralManagerDelegate, CBPeripheralDelegate 這兩個delegate.


例如在CBCentralManagerDelegate內有 centralManager(_:didDiscover:advertisementData:rssi:) 這個method, 透過rssi 我們可以知道裝置連線的訊號強弱判斷與裝置間的距離.



https://www.raywenderlich.com/52080/introduction-core-bluetooth-building-heart-rate-monitor

TitleAnimation for scroll down tableview[下拉tableview顯示title]

Demo code: github


Xcode Server Screenshot:





Dynamic UIImageView Size within UITableview [動態調整Imageview圖片高度]

OK, This is one of my code test problem when I interview iOS developer. In that time I didn't answer very well and I didn't get that job. But after I reorganized it, it's not so difficult to do it.

So, support we went download image from url and show it on UITableView, and we need to dynamic the ImageView in case some images are portrait, and some are landscape.

If we not doing anything, then they will look like:


As we can see first one is landscape image, but second one is portrait. And second one's image is squeezed by its frame. So we need to do some change when image is portrait.


Here is way we do:

1. Download image from internet url (we use SDWebImage sdk) and show on tableview
2. In  tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) we calculated the images ratio.
3. If is portrait image, then we update this row.


Here is demo code you can download: github

*In this project, you also can see I use custom class to save json data.

UITableview multi-custom cell [UITableview 使用多個自訂cell的處理]

It's easy to display tableview if just one cell templete, but when comes more then 2 or 3 different cells what to show on same UITableview, it will become very mass if we put all our logic code in side the fuction.

Just looks like:



So we put those codes in different methods and return to UITableViewCell , Then the code will look more clear.

Then we put the return cell into another function:

See! code looks much better!

Download source code here

iOS interview questions that I've been asked

最近面試問到的一些問題, 記錄一下:

1. What is cocoa and cocoa touch?

Cocoa and Cocoa Touch are the application development environments for OS X and iOS, respectively. Both Cocoa and Cocoa Touch include the Objective-C runtime and two core frameworks:
  • Cocoa, which includes the Foundation and AppKit frameworks, is used for developing applications that run on OS X.
  • Cocoa Touch, which includes Foundation and UIKit frameworks, is used for developing applications that run on iOS.

2. What's different between NULL and nil and Nil?

The difference is that while NULL represents zero for any pointer, nil is specific to objects (e.g., id) and Nil is specific to class pointers.

Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.

3. What's different between 'weak' and 'strong' property?

weak: will assign the incoming value to it without retaining it. You don't want to have control over the object's lifetime.

strong: (default)assigns the incoming value to it, it will retain the incoming value and release the existing value of the instance variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you point to it with a strong reference. Only once you set the property to nil will the object get destroyed.

strong属性指的是对这个对象强烈的占有!不管别人对它做过什么,反正你就是占有着!它对于你随叫随到。weak指的是对这个对象弱弱的保持着联系,每次使用的时候你弱弱的问它一句“还在吗”,如果没人回应(变成nil),就说明它已经离开你了(大概是被系统残忍的回收了吧)。

链接:https://www.zhihu.com/question/20350816/answer/22307399


retain cycle: Two objects hold a strong reference to each other, such that each instance keeps the other alive, the reference counts do not drop to zero, and the instances are not deallocated by ARC. This is known as a strong reference cycle. 



3.1. What is the difference between a weak reference and an unowned reference?

Both weak and unowned references do not create a strong hold on the referred object (a.k.a. they don't increase the retain count in order to prevent ARC from deallocating the referred object).

A weak reference allows the posibility of it to become nil (this happens automatically when the referenced object is deallocated), therefore the type of your property must be optional - so you, as a programmer, are obligated to check it before you use it (basically the compiler forces you, as much as it can, to write safe code).


An unowned reference presumes that it will never become nil during it's lifetime. A unowned reference must be set during initialization - this means that the reference will be defined as a non-optional type that can be used safely without checks. If somehow the object being referred is deallocated, then the app will crash when the unowned reference will be used.

A weak reference is just a pointer to an object that doesn't protect the object from being deallocated by ARC. While strong references increase the retain count of an object by 1, weak references do not.


4. What is ARC?

Automatic Reference Counting (ARC) is a compiler feature that provides automatic memory management of Objective-C objects. Rather than having to think about retain and release operations, ARC allows you to concentrate on the interesting code, the object graphs, and the relationships between objects in your application.

#automatic memory management, dealloc


5. What is atomic?

With "atomic", the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread.

atomic vs. nonatomic refers to the thread safety of the getter and setter methods that the compiler synthesizes for the property. atomic (the default) tells the compiler to make the accessor methods thread-safe (by adding a lock before an ivar is accessed) and nonatomic does the opposite. The advantage of nonatomic is slightly higher performance.

#atomic -> thread safety, nonatomic -> faster

6. What is BLOCK?

Blocks are a way of defining a single task or unit of behavior without having to write an entire Objective-C class.

You can use blocks to compose function expressions that can be passed to API, optionally stored, and used by multiple threads. Blocks are particularly useful as a callback because the block carries both the code to be executed on callback and the data needed during that execution.

#like closures in swift, callback API

7. What's different between CLASS and STRUCTURE in swift? 

The main difference is that structs are value types and classes are reference types. Structures cannot inherit from other types.

Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple reference to the same instance as happens with classes.

Structs there is much less need to worry about memory leaks.

8. What is a protocol?

It defines a list of required and optional methods that a class must/can implement if it adopts the protocol.

#define , required or optional methods, blueprint

9. What is UIAppliction?

UIApplication is the iOS singleton application base class.  It's a major role of  app’s application object is to handle the initial routing of incoming user events.


10. What is UIView? How to create custom UIView?

UIView is an object that manages the content for a rectangular area on the screen, it responsible for recognizing touches, gestures.

To create custom uiview, just create your own class subclassing UIView, then override initWithFrame or drawRect.

11. Optional type

A type that can represent either a wrapped value or nil. It shows the wrapped type's name with a trailing question mark (?). There are couple ways to unwrapping :  if let statement , guard statement, forced unwrapping. But forced unwrapping triggers a runtime error when the optional is nil. We should try to avoid it.

A common example of implicitly unwrapped optionals is how view controller define their IBOutlets.
It would be unwieldy(笨重的) to always unwrap each view outlet inside view controllers.

#question mark, exclamation mark, unwrapping 

11.1 Optional Chain
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

12. NSKeyedArchiver
Core data, NSKeyedArchiver and UserDefaults are three ways in which a programmer can persist data in between app launches. Though core data is slightly more complicated, it is useful when the stored information requires structure. NSKeyedArchiver is less complex and slower than core data, but is much simpler to use. UserDefaults is the simplest method to persist data.

13. Access Control

Open access and public access enable entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module. You typically use open or public access when specifying the public interface to a framework. The difference between open and public access is described below:

  • An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
  • A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.


Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.

File-private access restricts the use of an entity to its own defining source file. Use file-private access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.

Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.

Open access is the highest (least restrictive) access level and private access is the lowest (most restrictive) access level.

簡單來說:
keep private details of a class hidden from the rest of the app
keep internal details of a framework hidden from the client app


14. What is Core Data?

Core Data is a framework for managing an object graph. An object graph is nothing more than a collection of interconnected objects.

Core Data is not a database. 
Core Data isn't thread safe. Core Data expects to be run on a single thread.


How to use it?

When you start a new project in Xcode and open the template selection dialog, select the Use Core Data checkbox. A source file for the Core Data model is created as part of the template. That source file will have the extension .xcdatamodeld. Select that file in the navigator area to display the Core Data model editor.

1. open new project and check with "use Core Data"
2. open file have extension .xcdatamodelid, then xcode will display Cor Data model editor.
3. create entity and create attributes and relationships for the entity.
4. use NSManagedObject to manage data. (NSManagedObject represents a single object stored in Core Data; you must use it to create, edit, save and delete from your Core Data persistent store.)
5. NSFetchRequest is the class responsible for fetching from Core Data.


15. What is Grand Central Dispath(GCD)?

GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. A queue is actually a block of code that can be executed synchronously or asynchronously, either on the main or on a background thread. Queues are following the FIFO pattern.
Another important concept is the work item. A work item is literally a block of code that is either written along with the queue creation, or it gets assigned to a queue and it can be used more than once (reused).

When to Go for GCD or NSOperation?

when you want more control over queue (all above mentioned) use NSOperation and for simple cases where you want less overhead (you just want to do some work "into the background" with very little additional work) use GCD.

16. What is different between Frame and Bounds?

frame = a view's location and size using the parent view's coordinate system.(relative to the superview)
Important for: placing the view in the parent

bounds = a view's location and size using its own coordinate system
Important for: placing the view's content or subviews within itself

17. UIViewcontroller lifecircle

  • ViewDidLoad - Called when you create the class and load from xib. Great for initial setup and one-time-only work. It might be called several times if the view is unloaded due to low memory and then loaded again.
  • ViewWillAppear - Called right before your view appears, good for hiding/showing fields or any operations that you want to happen every time before the view is visible. Because you might be going back and forth between views, this will be called every time your view is about to appear on the screen.
  • ViewDidAppear - Called after the view appears - great place to start an animations or the loading of external data from an API.
  • ViewWillDisappear/DidDisappear - Same idea as ViewWillAppear/ViewDidAppear.
18. Singletion class

A singleton class returns the same instance no matter how many times an application requests it. A singleton object provides a global point of access to the resources of its class. Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource.

use the @synchronized pattern - and @synchronized is still the best way to do simple locking in Objective-C.

19. Closures

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

20. Autolayout

Auto Layout dynamically calculates the size and position of all the views in your view hierarchy(階層), based on constraints placed on those views.

21. Safe area

The Safe Area is the area in between System UI elements which are Status Bar, Navigation Bar and Tool Bar or Tab Bar. After iOS11, you can use SafeAreaLayoutGuide. By add constraints between your content and safe area anchors. This prevents your content from being obscured(模糊, 遮擋) by top and bottom bars.



利用AdMob 中介服務內部廣告影響使用者


1. 目前有相同內容的兩個App, 免費版的會有廣告, 付費版則是移除廣告。
2. 免費版的廣告平均約 USD 0.5 一天,但是免費版付費版的下載比約80:1

所以我希望利用AdMob的內部廣告方式,將使用者導向購買付費版。

第一次實驗: 曝光次數不限。

發現曝光次數爆增,但是效果卻沒有特別好,不會買的顯示再多次也不會影響,但是還會排擠到其它廣告的出現,導致廣告收入下降。

第二次實驗: 每人每天只會出現10次

效果和第一次差不多,但是廣告收入就沒掉的那麼嚴重。



但是比起以往一個月才2~3個購買付費版的情況下,現在幾乎2~3天就會有人花錢買了。
雖然收益不高,但是三個多月下來,付費的收益已經夠支付iOS的上架費用了(結果最後還是蘋果賺最多,上架要錢,成交也要抽)



Using swift 3 + Google firebase to make an check-in notice app

     This is not my first time to create an app with barcode scan function, but it's my first time to using Firebase Cloud Messaging for single device communication.

So, I decide to have 2 apps. One for client use, another for manager use:

1. CLIENT SIDE FUNCTIONS:

  • receive notification from firebase messaging.
  • show news data from firebase database.
  • register device token to firebase database.
  • others: make a phone call, FB share....






2. MANAGER SIDE FUNCTIONS:

  • can scan QR code.
  • can make a notification to a group or single device.
  • can publish news and saved it to firebase database, included images.









































----------------------------------------------

Workflow:

1. user installed client app -> register Token and SID to database

2. while manager scan the QR code content with SID -> database return device's token -> app call clouding messaging to make new notification.

-----------------------------------------------
Part code:

[continue]

APP 審核被拒_not obtain user consent before collecting the user's personal data.

話說每次審核都要看Apple的心情,心情好的話一天就審過,心情不好就要你提供一堆東西。
身分證明證件啦. 使用的第三方機器啦 巴拉巴拉。

今天又碰到了一個...

  • 17.1 - Apps cannot transmit data about a user without obtaining the user's prior permission and providing the user with access to information about how and where the data will be used
17.1 Details

We noticed that your app does not obtain user consent before collecting the user's personal data. 

Next Steps

To collect personal data with your app, you must make it clear to the user that their personal data will be uploaded to your server and you must obtain the user's consent before the data is uploaded.

- Starting with iOS 6, there are keys for specifying the reason the app will access the user's protected data. When the access prompt is displayed, the purpose specified in these keys is displayed in that dialog box. If your application will be transmitting protected user data, the usage string in your access request should clearly inform the user that their data will be uploaded to your server if they consent.



有趣的是同款App只是ICON不同的卻可以審過..... 0rz

Bubble Sort in Object C

-(void)bubbleSort{
    NSMutableArray *dataA = [NSMutableArray arrayWithArray:@[@15,@58,@33,@41,@28,@14]];
    int i,j;
    for (j = 1; j < dataA.count - 2; j ++) {
        for (i = 0; i < dataA.count - 1 ; i++) {
        if ([[dataA objectAtIndex:i] intValue] < [[dataA objectAtIndex:i+1] intValue]) {
            [dataA exchangeObjectAtIndex:i withObjectAtIndex:i+1];
        }
    }
    }
    NSLog(dataA);

}


OUT PUT: 58.41.33.28.15.14

Selection Sort in Object C

-(void)SelectionSort{
    NSMutableArray *dataA = [NSMutableArray arrayWithArray:@[@15,@58,@33,@41,@28,@14]];
    int max;
    
    for (int i = 0; i< dataA.count - 1; i++) {
        max = i;
        for (int j = i +1 ; j < dataA.count ; j++){
            if ([[dataA objectAtIndex:j] intValue] > [[dataA objectAtIndex:max] intValue]) {
                max = j;

            }
        }
        [dataA exchangeObjectAtIndex:i withObjectAtIndex:max];
    }
    NSLog(dataA);

}

iOS Push Key 產生步驟

雖然弄過很多次了,但只要其中一個小細節弄錯就會失敗,所以還是記一下避免自己忘記.

1. 產生CSR :  鑰匙圈存取 > 憑證輔助程式 > 從憑證授權要求憑證 > 一般名稱記得打比較好記的(如果有太多帳號或APP才方便管理) > 存到磁碟












2. 產生aps_development.cer : MemberCenter > AppIDs > 要用的App > Edit > Push Notifications > 把CSR丟上去 產生aps_development.cer

3. 產生.p12 :回到鑰匙圈 > 鑰匙 > 步驟一產生的憑證 > 選專用密鑰 > 右鍵輸出...

--------------------------------
4. 終端機開始結合:
[先把aps_development.cer 轉成pem]
$ openssl x509 -in aps_development.cer -inform der -out PushCert.pem
[把 p12 也轉成pem]
$ openssl pkcs12 -nocerts -out PushKey.pem -in PushKey.p12

[測試可不可以用]
$ openssl s_client -connect gateway.sandbox.push.apple.com:2195 
-cert PushCert.pem -key PushKey.pem

正常情況會出現:

如果這邊出現error字樣就是有錯誤,就要檢視哪個步驟出了問題.












[將兩個pem 結合給程式用]
$ cat PushCert.pem PushKey.pem > ck.pem

*2016/03/11 update:
Apple have changed the name of the certificate that is issued. You can now use the same certificate for both development and production. While you can still request a development only certificate you can no longer request a production only certificate.

Since the purpose of the certificate is no longer production only Apple has changed the common name to Apple Push Services. The functionality of the certificate is not affected.

ios enterprise program 申請札記

因為手上開發到一定階段的系統開始要上線封測了 XD 所以開始研究申請企業版的IOS帳號.
我把申請的程序記錄一下, 讓想申請的可以參考看看!

1. 先到apple id 申請ㄧ組帳號(也可以用原來的, 但因為是公司要用的, 所以還是申請一個新的), 申請時候所有的資料最好都用英文填, 不然會有亂碼!且蘋果會要求更正
2. 用剛申請的id 加入 apple developer
3. 進入apple developer後就可以開始走申請enterprise program的程序
4. 在第二步驟完成後, apple會打電話來確認您是否代表公司去申請這個program(放心, 對方是講中文的, 不過是大陸的口音)
這時候我再登入developer看我的申請進度就會顯示已經通過身份認證




5. 通過身份認證後進去就是同意他們的協議條款, 就直接agree吧, 除非你不想申請了
6. 然後會進入付款程序
7. 繳完NT9800後就會收到ㄧ封EMAIL提醒你他們已經正在處理了

8. 之後24小時內就會收到啓用通知, 按下EMAIL的連結就可以開始啓用了


這次從申請到上架部署學會了很多, 很高興公司給這個機會學習成長!


使用UIPicker View 建立郵遞區號 選擇器

基本上寫出2 column uipicker 的程式並不難!
實作看看吧!
Step 1. Xcode建立一個新的project.
Step 2. 在ViewController.xib 中拉UIPicker進去並把delegateSource 和 datasoure 設成file's Owner. 然後再拉一個label(lb_yourSelected)作為顯示picker選擇之用.

Step2. 在ViewController.h 中加入下列參數:
states -> 縣市名
zips -> 鄉鎮市名
zipCode -> 郵遞區號

Step 3. 在viewdidload中載入plist , 並把讀到的第一筆值存到相關陣列內.




Step 4. 開始設定UIPicker View的行為

這個核心就在didSelectRow這邊(上圖), 透過companent判斷目前使用者選擇的是“縣市”還是“鄉鎮縣市”, 如果選擇的是縣市則把該縣市內的所有鄉鎮資料撈出來丟到第二欄去 並要picker重新 reload 第二欄.






不動產相關法規 app

行動經紀人:不動產相關法規部分(

民法,土地法,土地法施行細則,土地稅法,土地稅法施行細則,不動產經紀業管理條例,不動產經紀業管理條例施行細則,不動產成交案件實際資訊申報登錄及查詢收費辦法,消費者保護法,消費者保護法施行細則,公平交易法,公寓大廈管理條例,公寓大廈管理條例施行細則,加值型及非加值型營業稅法,加值型及非加值型營業稅法施行細則,所得稅法,所得稅法施行細則,個人資料保護法,個人資料保護法施行細則,特種貨物及勞務稅條例(奢侈稅),特種貨物及勞務稅條例施行細則,平均地權條例,平均地權條例施行細則,農業發展條例,農業發展條例施行細則,建築法


可以搜尋條號和內容, 內頁可直接瀏覽上下筆



ipad 電子羅盤 測試

背景是ipad後方鏡頭, 配合指北針

ipad版 農民曆 測試

kal calendar 改的.