這一頁把 iOS 開發中最常被翻的幾段「小程式碼」集中整理:沙盒路徑怎麼取、相機怎麼開、檔案怎麼下載、截圖怎麼存、裝置號怎麼讀。每一段都短,但要用時總是查半天。
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Screenshot.png"];
宣告遵循 <UIImagePickerControllerDelegate>,然後:
// 1. 開啟相機
- (IBAction)Open:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
NSArray *tempMediaTypes =
[UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
picker.mediaTypes = tempMediaTypes;
picker.delegate = self;
picker.allowsImageEditing = YES;
}
[self presentViewController:picker animated:YES completion:nil];
}
拍照回呼——把結果存成檔案:
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if ([mediaType isEqualToString:@"public.image"]) {
UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
NSString *imageFile = [documentsDirectory stringByAppendingPathComponent:@"temp.jpg"];
// 若同名檔已存在,先刪掉再寫入
if ([fileManager fileExistsAtPath:imageFile]) {
[fileManager removeItemAtPath:imageFile error:&error];
}
imageView.image = image;
[UIImageJPEGRepresentation(image, 1.0f) writeToFile:imageFile atomically:YES];
}
else if ([mediaType isEqualToString:@"public.movie"]) {
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSString *videoFile = [documentsDirectory stringByAppendingPathComponent:@"temp.mov"];
if ([fileManager fileExistsAtPath:videoFile]) {
[fileManager removeItemAtPath:videoFile error:&error];
}
[videoData writeToFile:videoFile atomically:YES];
}
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:nil];
}
NSString *urlAsString = @"https://example.com/demo.zip";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:&error];
if (data != nil) {
NSString *target = @"/tmp/demo.zip";
if ([data writeToFile:target atomically:YES]) {
NSLog(@"保存成功");
} else {
NSLog(@"保存失敗");
}
} else {
NSLog(@"%@", error);
}
請注意:同步請求會封鎖主執行緒,畫面直接凍住。這段程式只適合寫工具腳本或早期教學;正式專案請改用 NSURLSession 的 dataTask 搭配 completion handler,或用 NSURLSessionDownloadTask 讓系統在背景替你下載(App 被終止後仍可續傳)。
先加入 AudioToolbox.framework:
#import <AudioToolbox/AudioToolbox.h> AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
UIDevice *device = [UIDevice currentDevice]; NSString *deviceUID = [[NSString alloc] initWithString:[device identifierForVendor].UUIDString];
這裡刻意用 identifierForVendor 而非 uniqueIdentifier:後者(UDID)自 iOS 5 起被標記為廢棄,iOS 7 之後完全移除,App Store 也會拒絕含有它的提交。若你需要更耐久的識別碼,實務上常見做法是自己產生 UUID 並存進 Keychain。
Unity 端先寫一個 JS 腳本掛到 ARCamera 上:
#pragma strict
function ScreenImage() {
Application.CaptureScreenshot("Screenshot.png");
}
iOS 端加上觸發按鈕:
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button1 setFrame:CGRectMake(0, 0, 30, 30)]; [button1 addTarget:self action:@selector(ScreenImage) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button1];
回呼函式:先叫 Unity 截圖,再把存下來的圖存進相簿。
-(void)ScreenImage {
// 呼叫 Unity 腳本函式
UnitySendMessage("ARCamera", "ScreenImage", "");
// 存進相簿
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Screenshot.png"];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
寫入相簿前,Info.plist 需具備 NSPhotoLibraryAddUsageDescription 這類用途說明字串,否則 iOS 10 之後會直接崩潰。
// 1. Documents 目錄(最完整的一種)
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath =
[documentsDirectory stringByAppendingPathComponent:filename];
// 2. 自訂宏(用 NSHomeDirectory 拼)
#define ABS_FILE_PATH(FILE_NAME) \
[NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(), FILE_NAME]
// 3. App bundle 內的資源
#define PACKAGE_FILE_PATH(FILE_NAME) \
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:FILE_NAME]
// 4. 直接用 NSBundle 查
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"txt"];
要牢記的差異是:bundle 是唯讀的,任何要寫入的檔案都必須放在 Documents、Library 或 tmp 這些沙盒目錄裡。把「讀的用 bundle、寫的用 Documents」當成反射動作,就不會再犯這類錯。
1. 整個螢幕截取
-(void)loadView {
[[UIApplication sharedApplication] setStatusBarHidden:YES
withAnimation:UIStatusBarAnimationSlide];
UIImage *mage = [UIImage imageNamed:@"image.png"];
UIImageView *imageView =
[[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[imageView setImage:mage];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
CGRect rect = CGRectMake(0, 0, 320, 480);
UIGraphicsBeginImageContext(rect.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextClipToRect(currentContext, rect);
CGContextDrawImage(currentContext, rect, mage.CGImage);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageView.image = image;
[self.view addSubview:imageView];
}
2. 整張圖的縮圖
-(void)loadView {
[[UIApplication sharedApplication] setStatusBarHidden:YES
withAnimation:UIStatusBarAnimationSlide];
UIImage *image = [UIImage imageNamed:@"image.png"];
// 用 rect 控制縮到多大
CGRect rect = CGRectMake(0, 0, 160, 240);
UIGraphicsBeginImageContext(rect.size);
CGContextRef currentContent = UIGraphicsGetCurrentContext();
CGContextClipToRect(currentContent, rect);
[image drawInRect:rect];
UIImage *thumb = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *contentView = [[UIImageView alloc] initWithFrame:rect];
contentView.image = thumb;
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[self.view addSubview:contentView];
}
3. 真正裁切出局部區域
- (void)loadView {
[[UIApplication sharedApplication] setStatusBarHidden:YES
withAnimation:UIStatusBarAnimationSlide];
UIImage *image = [UIImage imageNamed:@"image2.png"];
// 在原始圖上要裁出的矩形
CGRect rect = CGRectMake(33, 22, 140, 140);
// 裁切後在畫面上的顯示範圍
CGRect re = CGRectMake(0, 0, 140, 140);
UIImageView *contentView = [[UIImageView alloc] initWithFrame:re];
contentView.image = [UIImage imageWithCGImage:
CGImageCreateWithImageInRect([image CGImage], rect)];
self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
self.view.backgroundColor = [UIColor yellowColor];
[self.view addSubview:contentView];
}
注意 CGImageCreateWithImageInRect 建立的 CGImage 同樣需要 CGImageRelease;在 ARC 專案裡可以改用 UIImage 的 drawInRect: 搭配 UIGraphics 上下文來達成相同效果,就不必處理 C 家族的記憶體。
最後附一個可直接跑的小範例:在圖片上用手指拖曳畫出矩形,抬手時把該區域「剪」出來放到新位置。它把 touchesBegan/Moved/Ended 與 drawRect: 串起來,是理解 iOS 觸控與自繪流程很好的練習。
@interface imageView : UIView {
CGPoint starPoint;
CGPoint endPoint;
UIImage *image;
NSMutableArray *allMovePoints;
}
@end
@implementation imageView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
allMovePoints = [[NSMutableArray alloc] init];
self.frame = CGRectMake(0, 0, 320, 480);
image = [UIImage imageNamed:@"image.png"];
self.backgroundColor = [UIColor colorWithPatternImage:image];
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1, 0.2, 1.0, 1.0);
CGContextSetLineWidth(context, 2.0);
CGContextAddRect(context, CGRectMake(starPoint.x, starPoint.y,
endPoint.x - starPoint.x,
endPoint.y - starPoint.y));
CGContextStrokePath(context);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *t = [touches anyObject];
starPoint = [t locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *t = [touches anyObject];
endPoint = [t locationInView:self];
[self setNeedsDisplay];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
// 在原始圖上的裁切範圍
CGRect rect1 = CGRectMake(starPoint.x, starPoint.y,
endPoint.x - starPoint.x,
endPoint.y - starPoint.y);
// 放到畫面上另一個位置
CGRect re = CGRectMake(320 - endPoint.x + starPoint.x,
480 - endPoint.y + starPoint.y,
endPoint.x - starPoint.x,
endPoint.y - starPoint.y);
UIImageView *contentView = [[UIImageView alloc] initWithFrame:re];
contentView.tag = 3;
contentView.image = [UIImage imageWithCGImage:
CGImageCreateWithImageInRect([image CGImage], rect1)];
[self addSubview:contentView];
}
@end
這個 Demo 示範了三件常被一起用到的基礎觀念:setNeedsDisplay 觸發重繪、在 drawRect: 中取得繪圖上下文、以及把觸控座標換算成圖片上的裁切矩形。把這三者摸熟,多數「在圖片上框選」的需求都能自行變化出來。