2013年8月26日 星期一

NSString反轉字串

//文字反轉
-(NSString *)stringByReversed:(NSString*)sourceString{
    NSUInteger i = 0;
    NSUInteger j = sourceString.length - 1;
    unichar characters[sourceString.length];
    while (i < j) {
        characters[j] = [sourceString characterAtIndex:i];
        characters[i] = [sourceString characterAtIndex:j];
        i ++;
        j --;
    }
    if(i == j)
        characters[i] = [sourceString characterAtIndex:i];
    //從c array中,把字元一個一個寫出來
    return [NSString stringWithCharacters:characters length:sourceString.length];
} 
 
//利用文字反轉來取得網址中的檔案名稱
    NSString* tempString = [self stringByReversed:strURL];
    NSRange search = [tempString rangeOfString:@"/"];
    NSLog(@"%i", search.location);
    NSString* fileName =[self stringByReversed:[tempString substringToIndex:search.location]];
    NSLog(@"%@",fileName); 

2013年8月23日 星期五

iOS整合ZXing(QRcode & Barcode reader)


The issue you have encountered seems to be C++ standard library related.
Actually, whenever you see linker failures in relationship with standard library objects (e.g. std::string), you should check the project settings on all linked libraries and the app-project itself. They usually need to match!
The original ScanTest (which builds ZXingWidget as a subproject) uses the following settings and those need to match your App build-settings if you use the library as is.
For making sure, I created a brand-new project using Xcode 4.5. That project uses ZXingWidget as a prebuilt library but not as a subproject - I dont like subprojects for stuff that is not my own - though this specialty wont influence the results.
The important setting is C++ Standard Library - make sure that is set towards Compiler Default

如果依下列步驟整合進專案仍發生compile錯誤,則檢查你專案的Build Setting下的Apple LLVM compiler 4.2 - Language 裡的 C++ Standard Library是否設為Compiler Default

[以下節錄自http://noteforios.blogspot.tw/2012/09/zxing.html]
1.取得ZXing
連至http://code.google.com/p/zxing/取得,目前版本為2.2。

2.加入ZXing到專案中
ZXing支援很多平台,請依序點選進入資料夾中

zxing >iphone > ZXingWidget

將ZXingWidget.xcodeproj拖曳至專案中,如果出現提示,請注意請勿勾選複製選項,請以參考的方式加入。

3.設定Build Phases
選擇專案TAGETS,選擇Build Phases分頁
3.1 在Target Dependencies中,加入ZXingWidget (ZXingWidget)
3.2 在Link Binary With Libraries加入所需framework

  • libZXingWidget.a
  • libiconv.dylib
  • CoreVideo.framework
  • CoreMedia.framework
  • AVFoundation.framework
  • AudioToolbox.framework
  • AddressBook.framework
  • AddressBookUI.framework
4.設定Build Setting
在Build Setting中搜尋"Header Search Paths"
點選"+"號,增加搜尋路徑,這邊記得要提供完整路徑,
Full Path../zxing/cpp/core/src (選non-recursive)
Full Path../zxing/iphone/ZXingWidget/Classes (選recursive)
加入完成後要確定有被勾選才行

5.import
#import <ZXingWidgetController.h>
#import <QRCodeReader.h>

注意事項:
  1. 資料夾名稱請不要包含"空白",會導致XCode誤判。
  2. 因有使用到C++的編譯器,請記得將副檔名由.m變更為.mm。
  3. #import <qrcodereader.h>請寫在.mm中,不然編譯會錯誤。
  4. ZXingWidget.xcodeproj的Compiler要注意
  5. 目前不確定是否支援ARC與storybard,所以請不要使用該功能。

2013年8月12日 星期一

不存在則下載後reload,已經存在則直接reload

//下載影片後reload
- (void)downloadVideoAndReload{
    NSString *urlAsString = @"http://yourURL/yourVideo.mp4";
    NSURL *url = [NSURL URLWithString:urlAsString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
   
    //取得文件目錄
    NSString* documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //完整檔案路徑
    NSString* filePath = [documentsDir stringByAppendingString:@"marq-playboy-360p.mp4"];
    EAGLView* arView = [arParentViewController getARView];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
        NSLog(@"yourVideo.mp4不存在,開始下載");
        [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *responce, NSData *data, NSError *error) {
            if ([data length] > 0 && error == nil) {
               
                //將資料寫入檔案
                [data writeToFile:filePath atomically:YES];
               
                NSLog(@"成功存檔至%@",filePath);
                                    // For each video-augmented target
                    for (int i = 0; i < NUM_VIDEO_TARGETS; ++i) {
                        // Load a local file for playback and resume playback if video was
                        // playing when the app went into the background
                        VideoPlayerHelper* player = [arView getVideoPlayerHelper:i];
                        NSString* filename;

                        switch (i) {
                            case 0:
                                //filename = @"/var/mobile/Applications/56AA8666-2109-49C5-A649-F7600240CF15/Library/Documentationht-inception-360p.mp4";
                                filename = filePath;
                                break;
                            default:
                                filename = @"yourVideo.mp4";
                                break;
                        }
                       
                        if (NO == [player load:filename playImmediately:NO fromPosition:videoPlaybackTime[i]]) {
                            NSLog(@"Failed to load media");
                        }
                    }


            }
            else if ([data length] == 0 && error == nil){
                NSLog(@"沒有被下載");
            }
            else if (error != nil){
                NSLog(@"Err : %@",error);
            }
        }];
       
       
    }else{
        NSLog(@"yourVideo.mp4存在");

        // For each video-augmented target
        for (int i = 0; i < NUM_VIDEO_TARGETS; ++i) {
            // Load a local file for playback and resume playback if video was
            // playing when the app went into the background
            VideoPlayerHelper* player = [arView getVideoPlayerHelper:i];
            NSString* filename;
           
            switch (i) {
                case 0:
                    filename = filePath;
                    break;
                default:
                    filename = @"yourVideo.mp4";
                    break;
            }
           
            if (NO == [player load:filename playImmediately:NO fromPosition:videoPlaybackTime[i]]) {
                NSLog(@"Failed to load media");
            }
        }


    }
}

CIImage, UIImage, CGImageRef

這三者都是Image的物件導向表示法
UIImage是用來表示iOS中的image資料,他是內建於UIKit.framework
CIImage是使用CoreImage.framework來對影片做操作的主要datatype
CGImageRef is an opaque type that represents a Quartz 2D drawing environment.

CGImageRef可以視為UIKit與CoreImage之間的介接,如下所示
UIImage *image = [imageView image];
CGImageRef cgImage = image.CGImage;
CIImage *coreImage = [CIImage imageWithCGImage:cgImage];


//從透過CIContext將CIImage繪製成CGImageRef
CGImageRef cgImage = [self.imageContext createCGImage:coreImage fromRect:[coreImage extent]];
//再由CGImageRef轉換成UIImage
[self.imageView setImage:[UIImage imageWithCGImage:cgImage]];

動態下載.pod檔

In cocos3D you can create a node from a pod file by simply executing:
[CC3PODResourceNode nodeFromResourceFile:podFileName];
 
Here you can find a full working sample.
If your pod file is available online, you could first download it locally:
NSURL *url = [NSURL URLWithString:YOUR_URL_HERE];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];
 
then pass filePath to nodeFromResourceFile.
filePath identifies a file residing in the user documents directory (one of the few places where you can write files to, under iOS):
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"PODFILE.pod"];

If you want to save to a temporary directory, use:
NSTemporaryDirectory()
instead of documentsDirectory.

2013年8月9日 星期五

xcode的支援檔預設安裝位置

/Library/Application Support/Developer/Shared/Xcode/

安裝cocos3d

重點:
一,把cocos3d下載解壓
二,把cocos3d跟cocos2d放在同一層的資料夾
三,在cocos3d資料夾中以terminal執行sudo ./install-cocos3d.sh -f -2 "../cocos2d-iphone-1.0.1"
四,注意目前cocos3d 0.7.2版只可整合進cocos2d 1.x版中

Installation
------------

The cocos3d framework is built on cocos2d 1.x. Before installing cocos3d,
you must download and install the cocos2d 1.x SDK from:

http://www.cocos2d-iphone.org/download

*** PLEASE NOTE THAT cocos3d 0.7.2 IS NOT COMPATIBLE WITH cocos2d 2.x. ***
***     BE SURE TO DOWNLOAD cocos2d 1.x FOR USE WITH cocos3d.          ***

Unzip the cocos3d distribution file (which you've probably already done,
otherwise you wouldn't be reading this document).

Open a Terminal session, navigate to the unzipped cocos3d distribution
directory and run the install-cocos3d script as follows:

./install-cocos3d.sh -f -2 "path-to-cocos2d-sources"

For example:

./install-cocos3d.sh -f -2 "../../cocos2d/cocos2d-iphone-1.1"

The cocos2d source code must be available and identified using the -2 switch so that the
installer can link the cocos2d libraries to the cocos3d templates and demo projects.

If you encounter 'rsync' errors during installation, it's typically because you are trying
to run the installer without first navigating to the cocos3d distribution directory.
Be sure to run the installer from the cocos3d distribution directory.

That's it!

安裝及移除cocos2d

A. cocos2d 官網: http://www.cocos2d-iphone.org/

B. 下載穩定版本(Stable version): http://www.cocos2d-iphone.org/download

C. 安裝方式:
   1. 解壓縮下載的檔案: cocos2d-iphone-1.0.1.tar.gz
   2. 在 Terminal 下, 到解壓縮目錄內執行:
       $ cd cocos2d-iphone-1.0.1.tar.gz
        $ sudo ./install-templates.sh
   3. 可以看到以下的安裝訊息:
      Installing cocos2d template:
      /Library/Application Support/Developer/Shared/Xcode/Project Templates/cocos2d 0.99.4/cocos2d Application/

      Installing cocos2d + box2d template:
      /Library/Application Support/Developer/Shared/Xcode/Project Templates/cocos2d 0.99.4/cocos2d Box2d Application/

      Installing cocos2d + chipmunk template:
      /Library/Application Support/Developer/Shared/Xcode/Project Templates/cocos2d 0.99.4/cocos2d Chipmunk Application/

      creating destination directory:
      /Library/Application Support/Developer/Shared/Xcode/File Templates/cocos2d 0.99.4/

D. 移除方式:
   刪除: C 安裝後所產生的目錄即可.

轉貼來源:http://itouchs.blogspot.com/2010/11/iphone-16-cocos2d.html

2013年8月6日 星期二

Calculate the MD5 Hash of a String in Objective-C

#import <CommonCrypto/CommonDigest.h>

- (NSString *) encodeString:(NSString *) s {
   const char *cStr = [s UTF8String];
   unsigned char result[CC_MD5_DIGEST_LENGTH];
   CC_MD5(cStr, strlen(cStr), result);
   NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
   for(int i = 0; i < CC_MD5_DIGEST_LENGTH; ++i) {
      [result appendFormat:@"%02x", result[i]];
   }       
   return [NSString stringWithString:result];
}      

2013年8月5日 星期一

動態匯入QCAR資料庫

(尚未實際測試)
just download that file from network, store it within application directories and load it like the sample data bundled with the app

NSString * pathToDownloadedFile; //should have path to your file

QCAR::DataSet *dataSet = nil;
QCAR::TrackerManager& trackerManager = QCAR::TrackerManager::getInstance();
QCAR::ImageTracker* imageTracker = static_cast<QCAR::ImageTracker*>    (trackerManager.getTracker(QCAR::Tracker::IMAGE_TRACKER));
dataSet = imageTracker->createDataSet();
dataSet->load([pathToDownloadedFile cStringUsingEncoding:NSASCIIStringEncoding], QCAR::DataSet::STORAGE_ABSOLUTE);


imageTracker->activateDataSet(dataSet);