顯示具有 Objective-C 標籤的文章。 顯示所有文章
顯示具有 Objective-C 標籤的文章。 顯示所有文章

2013-02-18

iOS App 在背景狀態下持續更新 GPS 回報之位置

一般 App 在進入 Background 背景狀態之後就會被暫停執行,但做以下設定之後 App 可在此狀態持續更新 GPS 回報的使用者座標位置 :

1. 在 App 的 Info.plist 檔案的 Required device capabilities 項目底下加入 location-services 及 gps
2. 同樣在該檔案的 Required background modes 底下加入 App registers for location updates

設定 Info.plist 檔案之 Required device capabilities 及 Required background modes

接下來的範例是開一個 empty iOS Application project 然後加入一些程式碼來測試 :

1. 為 project 加入 CoreLocation.framework

加入 CoreLocation.framework 至 Linked Frameworks and framework

2. 在 AppDelegate.h 檔案增加 / 修改程式碼  :
#import <CoreLocation/CoreLocation.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>
3. 在 AppDelegate.cpp 檔案增加程式碼 :
CLLocationManager* locationManager =nil;
- (void)startStandardUpdates
{
    if (nil == locationManager)
        locationManager = [[CLLocationManager alloc] init];
    
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"update location err-\n%@", error);
}

// Delegate method from the CLLocationManagerDelegate protocol.
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation* location = [locations lastObject];
    NSString* pp =[NSString stringWithFormat:@"http://192.168.11.6:10001/?lat=%.3f&lon=%.3f", location.coordinate.latitude, location.coordinate.longitude];
    
    NSURL* response =[NSURL URLWithString:pp];
    NSString* response_str =[NSString stringWithContentsOfURL:response encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@, response of report=%@", pp, response_str);
}

函數 didUpdateLocations 在每次更新 GPS 回報的位置時使用 NSURL 以 http 方式向伺服器 192.168.11.6 以 GET 方式回報位置 (lat, lon)。

4. 在 AppDelegate.cpp 檔案之函數 didFinishLaunchingWithOptions 內加入程式碼 :
[self startStandardUpdates];
在程式啟動時呼叫 startStandardUpdates 開始取得 GPS 回報的使用者位置。

2012-09-17

Convert char** (string array) to C# string[]

底下範例是將 C/C++ 的字串陣列指標 (char**) 轉成 C# 內部使用的 string[] :

C/C++ 端的函數指標為 :
typedef void (* pCBFunc)(int, char**);

對應的 C# 端的函數為 :
public static void callback(int nArrsz, IntPtr pStringArray)
{
    string[] data = new string[nArrsz];
    IntPtr tmpPtr = pStringArray;
 
    for (int i = 0; i < nArrsz; ++i)
    {
        IntPtr strPtr = 
            (IntPtr)Marshal.PtrToStructure(tmpPtr, typeof(IntPtr));
        data[i] = Marshal.PtrToStringAuto(strPtr);
 
        tmpPtr = new IntPtr(tmpPtr.ToInt64() + IntPtr.Size);
    }
}
其中的 int nArrsz 為字串數目,IntPtr pStringArray 為字串陣列 ( 對應至 C 的 char** ) ,string[] data 是轉型後的資料。

2012-04-24

Unity 3D 在 iOS 上顯示中文字串


之前使用 Unity3D 寫遊戲程式都是以 Dynamic Font 功能來顯示中文字串,最近才發現這功能不支援 iOS,因此若要在 iOS 上使用 Dynamic Font 就得自己做了,幸運的是實作起來並不複雜,底下敘述如何將中文字串轉成圖片 ( Texture2D ) 的方法 : ( 概略是利用 iOS 內建的 Font Renderer 先把字串畫在主記憶體裡,再利用 OpenGL 指令將記憶體裡字串的圖片轉成貼圖 )

全部範例檔案有三個 :
1. main.cs
    a. 放在 Assets 目錄底下
    b. 此 Script 依附在 Main Camera 上

2. dynaFont.cs
    a. 放在 Assets/Plugins 目錄底下
    b. 此檔案為 unity3d 內部 script 與 plugin 之間的介面

3. dynaFont.m
    a. 放在 Assets/Plugins/iOS 目錄底下 (轉成 xcode project 時將自動引入)
    b. 不需事先編譯

首先看 main.cs 檔案內容 :


using UnityEngine;
using System.Collections;

public class main : MonoBehaviour {

    // Use this for initialization
    void Start ()
    {
        int nWidth =128;
int nHeight =128;

        //產生 128x128 (注意大小為2冪次方)之 texture
Texture2D tex =
            new Texture2D(
                nWidth, 
                nHeight, 
                TextureFormat.Alpha8, 
                false);

        //把中文字畫在 texture 上
        genTexture(
            tex.GetNativeTextureID(), 
            "中文測試", 
            "Arial", 
            10, 
            128, 
            128);
}
}


dynaFont.cs 檔案內容如下 :


using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
//
//此為 unity3d 內部程式呼叫外部 plugin 函數之間的介面
//
public class dynaFont
{
    //指示 getTexture 為外部 plugin 函數
  [DllImport("__Internal")]
  public static extern bool genTexture(
        int nTexID, 
        string strText, 
        string strFontName, 
        int nFontSz, 
        int nTexWidth, 
        int nTexHeight);
}


dynaFont.m 檔案內容如下 :


#import <Foundation/Foundation.h>
//
// 將 char 指標 (對應 C# 的 string) 轉成 iOS 字串格式 (NSString)
//
NSString* dynaFont_GetString(const char* pChar)
{
  if (pChar ==NULL)
      return [NSString stringWithUTF8String:""];
return [NSString stringWithUTF8String:pChar];
}


//
// 利用 NSString 的 drawInRect 畫出字串後再以 glTexImage2D 產生貼圖
//
bool genTexture( int nTexID, 
                 const char* pStrText, 
                 const char* pStrFontName, 
                 int nFontSz, 
                 int nTexWidth, 
                 int nTexHeight)
{
    unsigned char* pData =
        (unsigned char*)calloc(nTexWidth, nTexHeight);

    CGColorSpaceRef pcs =CGColorSpaceCreateDeviceGray();
    CGContextRef pcon =
        CGBitmapContextCreate(
            pData, 
            nTexWidth, 
            nTexHeight, 
            8, 
            nTexWidth, 
            pcs, 
            kCGImageAlphaNone);
    CGColorSpaceRelease(pcs);

    if (!pcon)
    {
      free(pData);
      return false;
    }
    else
    {
      CGContextSetGrayFillColor(pcon, 1.0f, 1.0f);

    CGSize rc =CGSizeMake(nTexWidth, nTexHeight);
    UIFont* pf =
            [ UIFont
              fontWithName:dynaFont_GetString(pStrFontName) 
              size:nFontSz];

    UIGraphicsPushContext(pcon);
        [ dynaFont_GetString(pStrText)
          drawInRect:CGRectMake(0,0,rc.width, rc.height) 
          withFont:pf lineBreakMode:UILineBreakModeWordWrap 
          alignment:UITextAlignmentLeft];
    UIGraphicsPopContext();

    glBindTexture(GL_TEXTURE_2D, nTexID);
    glTexImage2D(
            GL_TEXTURE_2D, 
            0, 
            GL_ALPHA, 
           (GLsizei)nTexWidth, (GLsizei)nTexHeight, 
            0, 
            GL_ALPHA, 
            GL_UNSIGNED_BYTE, 
            pData);
    CGContextRelease(pcon);

    free(pData);
    }
    return true;
}


2011-11-13

Objective-C 執行緒同步 ( NSCondition )

撰寫多執行緒程式都會碰到資料同步問題,objc 在這邊可使用 NSCondition 來達成,底下是 NSCondition 與 C#,C++用法比較:
Objective-C 的用法如下: 
NSCondition* pLock =[NSCondition new];
[pLock lock];
{ 
    //...
}
[pLock unlock];
[pLock release];



C++ 的用法如下:  HANDLE m_Handle =CreateSemaphore( NULL, 1, 1, L"SemaphoreName" );

WaitForSingleObject( m_Handle, nWaitTime );
{ 
    //...
}
ReleaseSemaphore( m_Handle, 1, NULL );
CloseHandle( m_Handle );



C# 的用法如下: 
private static AutoResetEvent m_Handle =new AutoResetEvent( true ); 
m_Handle.WaitOne(); 
{ 
    //...
}
m_Handle.Set();
其它有關執行緒同步的文章參考這篇。

Objective-C 多執行緒 ( NSOperationQueue )

objc 的 NSOperationQueue 跟 Thread Pool 很類似,用起來也非常的容易,這邊把 Operation 看成 Thread Task , Operation Queue 則看成 Thread Pool 。
底下舉一個簡單的例子:主執行緒使用另一個執行緒印出 “i am taskClass” 字串
//taskClass 負責印出 “i am taskClass” 字串 
@interface taskClass : NSOperation {
}
//main 繼承於 NSOperation, 執行緒啟動時將執行這個函數
-(void) main;
@end


 
@implementation taskClass
-(void) main
{
    NSAutoreleasePool* nsap =[NSAutoreleasePool new];
    NSLog(@"i am taskClass");
    [nsap drain];
}
@end



//主程式
int main (int argc, const char * argv[])
{
    NSAutoreleasePool* nsap =[NSAutoreleasePool new];

    //建立 NSOperationQueue
    NSOperationQueue* nsoq =[NSOperationQueue new];

    //設定最多同時執行的執行緒數
    [nsoq setMaxConcurrentOperationCount:10];

    //建立 taskClass
    taskClass* myTaskClass =[taskClass new];

    //將 taskClass 丟給 NSOperationQueue
    //NSOperationQueue 會分配執行緒去執行 taskClass 的 main 函數

    [nsoq addOperation:myTaskClass];

    //等待 Queue 裡所有的 Operation 執行完畢
    [nsoq waitUntilAllOperationsAreFinished];
   
    [myTaskClass release];
   
    [nsoq release];
   
    [nsap drain];
}
此外,假如 Operation 執行的程式屬於無限迴圈,則在主程式要結束時,可用 cancelAllOperations 函數來通知 Queue 裡的 Operation 中斷迴圈並結束程式,舉例如下:
@interface taskClass : NSOperation {
}
-(void) main;
@end


@implementation taskClass
-(void) main
{
    //檢查 Cancelled 是否為 true, 否則繼續執行
    while ([self isCancelled]==false) {
        //迴圈工作... 
    }
}
@end


//主程式
int main (int argc, const char * argv[])
{
    NSAutoreleasePool* nsap =[NSAutoreleasePool new];

    NSOperationQueue* nsoq =[NSOperationQueue new];
    [nsoq setMaxConcurrentOperationCount:10]; 

    taskClass* myTaskClass =[taskClass new]; 
    [nsoq addOperation:myTaskClass];


    //通知所有執行中的 Operation 中斷執行
    [nsoq cancelAllOperations]; 

    [nsoq waitUntilAllOperationsAreFinished];

    [myTaskClass release];

    [nsoq release];

    [nsap drain];
}

2011-11-07

Objective-C dot(.) 與 arrow(->)

objc 在這裡跟 C++ 一樣,可以透過 (.) 及 (->) 來存取類別(class) 的成員 “變數”,但在 objc 的 property 機制影響之下,有些地方可能會搞不清楚。底下做了一些整理。
假如目前有一個 class 如下:
定義:
@interface classA :NSObject{
@private
    int val;
@public
    int pubVal;
   
}

-(void) initVal: (int) newVal;
-(void) printVal;
@end

實作:
@implementation classA
@synthesize val, pubVal;
-(void) initVal:(int)newVal
{
    val =newVal;
}

-(void) printVal
{
    NSLog(@"val=%d", val);
}

@end
dot(.) 與 arrow(->) 的操作:
classA* bbb =[classA new];
//dot notation
//設定值

bbb.pubVal =5;        //dot 透過 property 機制存取, 同等於 [bbb setPubVal:5];
bbb.val =6;              //dot 透過 property 機制存取, 同等於 [bbb setVal:6];
(*bbb).pubVal =7;    //dot 可直接存取 @public member
//(*bbb).val =8;      //Error, 不是 @public member
//取值
int tmpVal;
tmpVal =bbb.pubVal;      //tmpVal =7,同等於tmpVal =[bbb pubVal];
tmpVal =bbb.val;           //tmpVal =6,同等於tmpVal =[bbb val];
tmpVal =(*bbb).pubVal;  //tmpVal =7
//tmpVal =(*bbb).val;  //Error, 不是 @public member
//arrow notation
//設定值

bbb->pubVal =5;     //arrow 可直接存取 @public member 
//bbb->val =5;             //Error, 不是 @public member
//取值
tmpVal =bbb->pubVal;   //tmpVal =7
//tmpVal =bbb->val;     //Error, 不是 @public member

//使用函數操作
//設定值

[bbb setPubVal:5];  //setPubVal 函數由 property 機制自動產生
[bbb setVal:6];        //setVal 函數由 property 機制自動產生
//取值
tmpVal =[bbb pubVal];
tmpVal =[bbb val];

[bbb initVal:10];
[bbb printVal];

[bbb release];
執行的結果為:
val=10

2011-11-04

Objective-C SEL ( Selector )

暫時先“想像” objc 的 SEL 就像是 C 的函數指標(但在 objc 裡另外還有 IMP, 其定義同等於 C 的函數指標),例如現在有一個類別如下:
定義:
@interface classA :NSObject{
@private
    int val;
}

-(void) initVal: (int) newVal;
-(void) printVal;
@end


實作內容:
@implementation classA
-(void) initVal:(int)newVal
{
    val =newVal;
}

-(void) printVal
{
    NSLog(@"val=%d", val);
}

@end
SEL ( Selector ) 的操作範例如下:
id ppp =[classA new];
[ppp initVal:99];
SEL printPP1 =@selector(printVal);
SEL printPP2 =NSSelectorFromString(@"printVal");

if ([ppp respondsToSelector:printPP1])
    [ppp performSelector:printPP1];

if ([ppp respondsToSelector:printPP2])
    [ppp performSelector:printPP2];

[ppp release];
其中的 printPP1, printPP2 皆指向 classA 的 printVal 函數, 因此 SEL 的產生方式可以有 @selector 或是 NSSelectorFromString 兩種。
執行的結果為:
val=99
val=99