這篇整理 iOS 開發中關於檔案路徑、相機拍照、下載、震動、截圖等基礎但高頻的 operations,方便隨時查閱。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Screenshot.png"];
先宣告 <UIImagePickerControllerDelegate>,接著建立 image picker:
- (IBAction)openCamera:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
picker.delegate = self;
picker.allowsImageEditing = YES;
}
[self presentViewController:picker animated:YES completion:nil];
}
拍攝/選取完成後的回呼,根據 mediaType 分別處理照片與影片:
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
if ([mediaType isEqualToString:@"public.image"]) {
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
NSString *imageFile = [docPath stringByAppendingPathComponent:@"temp.jpg"];
// 同名檔存在時先刪除,避免寫入失敗
if ([fm fileExistsAtPath:imageFile]) {
[fm removeItemAtPath:imageFile error:nil];
}
[UIImageJPEGRepresentation(image, 1.0f) writeToFile:imageFile atomically:YES];
}
else if ([mediaType isEqualToString:@"public.movie"]) {
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSString *videoFile = [docPath stringByAppendingPathComponent:@"temp.mov"];
if ([fm fileExistsAtPath:videoFile]) {
[fm removeItemAtPath:videoFile error:nil];
}
[[NSData dataWithContentsOfURL:videoURL] writeToFile:videoFile atomically:YES];
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
NSURL *url = [NSURL URLWithString:@"https://example.com/demo.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if (data) {
NSString *target = [docPath stringByAppendingPathComponent:@"demo.zip"];
NSLog(@"%@", [data writeToFile:target atomically:YES] ? @"保存成功" : @"保存失敗");
} else {
NSLog(@"%@", error);
}
提醒:同步請求會阻塞主線程,正式環境請改用 NSURLSession 的 dataTaskWithRequest: 並搭配 completion handler。
加入 AudioToolbox.framework 後:
#import <AudioToolbox/AudioToolbox.h> AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
UIDevice *device = [UIDevice currentDevice]; NSString *deviceUID = [[NSString alloc] initWithString:[device identifierForVendor].UUIDString];
注意:舊寫法 [device uniqueIdentifier] 已被 Apple 移除,請改用 identifierForVendor。
JavaScript 腳本掛在 ARCamera 上:
function ScreenImage() {
Application.CaptureScreenshot("Screenshot.png");
}
Objective-C 端建立按鈕:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button setFrame:CGRectMake(0, 0, 30, 30)]; [button addTarget:self action:@selector(screenImage) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button];
回應方法:先呼叫 Unity 腳本截圖,再從 Documents 讀出檔案寫入相簿:
- (void)screenImage {
UnitySendMessage("ARCamera", "ScreenImage", "");
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docPath stringByAppendingPathComponent:@"Screenshot.png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
1. Documents 目錄(可寫入,iTunes 可見):
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *path = [doc stringByAppendingPathComponent:filename];
2. 自訂宏(同上,但更簡潔):
#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. 直接以資源名稱取用(最推薦,省去組字串的麻煩):
NSString *path = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"txt"];
第一種:整個螢幕截取——建立與螢幕同尺寸的 image context,把圖畫上去再取出:
CGRect rect = CGRectMake(0, 0, 320, 480); UIGraphicsBeginImageContext(rect.size); CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextClipToRect(ctx, rect); CGContextDrawImage(ctx, rect, image.CGImage); UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
第二種:整張圖縮圖——用 drawInRect 指定目標尺寸,讓系統自動縮放:
CGRect rect = CGRectMake(0, 0, 160, 240); UIGraphicsBeginImageContext(rect.size); [image drawInRect:rect]; UIImage *thumb = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
第三種:真正裁切局部區域——用 CGImageCreateWithImageInRect 取出指定矩形:
CGRect rect = CGRectMake(33, 22, 140, 353); // 欲裁切的區域 UIImage *cropped = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage, rect)];
透過 touchesBegan/touchesMoved 記錄起訖點,在 drawRect 畫出選取框,抬手時再依框線裁切:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
starPoint = [[touches anyObject] locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
endPoint = [[touches anyObject] locationInView:self];
[self setNeedsDisplay]; // 觸發重繪
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx, 1, 0, 0, 1);
CGContextSetLineWidth(ctx, 2.0);
CGContextAddRect(ctx, CGRectMake(starPoint.x, starPoint.y,
endPoint.x - starPoint.x, endPoint.y - starPoint.y));
CGContextStrokePath(ctx);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
CGRect clipRect = CGRectMake(starPoint.x, starPoint.y,
endPoint.x - starPoint.x, endPoint.y - starPoint.y);
UIImage *cropped = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage, clipRect)];
UIImageView *resultView = [[UIImageView alloc] initWithImage:cropped];
[self addSubview:resultView];
}
最後提醒:凡是用 UIGraphicsBeginImageContext 建立的 context,都必須成對呼叫 UIGraphicsEndImageContext,否則在大量截圖的情境下會造成記憶體累積。