以下整理三天的學習筆記:自繪三角形、三種多執行緒方案、網路狀態監測,以及同步/非同步與 GET/POST 請求的差異。
需求是讓使用者任意點擊螢幕三點,即連成一個三角形。做法是記錄觸摸點,然後在 drawRect: 中重繪。
- (void)drawRect:(CGRect)rect {
// 取得繪圖上下文
CGContextRef context = UIGraphicsGetCurrentContext();
CGPoint addLines[] = {
firstPoint, secondPoint, thirdPoint, firstPoint,
};
// 加入線條路徑
CGContextAddLines(context, addLines, sizeof(addLines) / sizeof(addLines[0]));
// 描邊
CGContextStrokePath(context);
}
觸摸事件負責收集座標並觸發重繪:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
[pointArray addObject:[NSValue valueWithCGPoint:point]];
// 只保留最近三個點
if (pointArray.count > 3) {
[pointArray removeObjectAtIndex:0];
}
if (pointArray.count == 3) {
firstPoint = [[pointArray objectAtIndex:0] CGPointValue];
secondPoint = [[pointArray objectAtIndex:1] CGPointValue];
thirdPoint = [[pointArray objectAtIndex:2] CGPointValue];
}
[self setNeedsDisplay]; // 關鍵:觸發 drawRect 重新呼叫
}
注意 addLines 陣列中刻意把 firstPoint 放在最後一項,這樣路徑會自動閉合成三角形。而 setNeedsDisplay 是整個流程的樞紐——它只是標記「需要重繪」,真正的繪製會在下次更新週期由系統呼叫 drawRect:,因此不要在 drawRect: 以外的地方直接畫圖。
iOS 提供三種多執行緒方案,抽象層級由低到高:
NSLock、NSCondition)也有系統開銷。NSOperation 與 NSOperationQueue 為核心。NSOperation 是抽象類別,可用其子類 NSInvocationOperation、NSBlockOperation,或自行繼承。你不必操心執行緒管理,只需專注在「要做什麼」。NSThread 的兩種建立方式:
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument; + (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument;
前者是實例方法(建立後需自行 start,可先設定優先級等屬性),後者為類別方法(建立後立即執行)。selector 只能有一個參數且不可有回傳值。
#define kURL @"https://avatar.csdn.net/2/C/D/1_totogo2010.jpg"
- (void)viewDidLoad {
[super viewDidLoad];
NSInvocationOperation *operation =
[[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(downloadImage:)
object:kURL];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];
}
- (void)downloadImage:(NSString *)url {
NSURL *nsUrl = [NSURL URLWithString:url];
NSData *data = [[NSData alloc] initWithContentsOfURL:nsUrl];
UIImage *image = [[UIImage alloc] initWithData:data];
[self performSelectorOnMainThread:@selector(updateUI:)
withObject:image
waitUntilDone:YES];
}
- (void)updateUI:(UIImage *)image {
self.imageView.image = image;
}
控制線程池併發數量:
[queue setMaxConcurrentOperationCount:5];
預設值為 -1,代表不限制,會同時執行佇列中的所有操作。實務上建議明確設定,避免一次送出幾十個請求把系統與網路打爆。
在 AppDelegate 中宣告屬性並開始監聽:
@property (retain, nonatomic) Reachability *hostReach;
// 註冊通知,實現全域監測
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
self.hostReach = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
[self.hostReach startNotifier];
- (void)reachabilityChanged:(NSNotification *)note {
Reachability *reach = [note object];
NSParameterAssert([reach isKindOfClass:[Reachability class]]);
switch ([reach currentReachabilityStatus]) {
case NotReachable:
[self AlertViewShow:@"無網絡,請檢查網絡設置"];
break;
case ReachableViaWiFi:
[self AlertViewShow:@"當前網絡為 WIFI 網絡"];
break;
case ReachableViaWWAN:
[self AlertViewShow:@"當前網絡為 2G 或 3G 網絡"];
break;
default:
[self AlertViewShow:@"error"];
break;
}
}
- (void)AlertViewShow:(NSString *)mes {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"通知"
message:mes
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
使用時記得把 Reachability 的 .h 與 .m 加入專案。要留意的是 Reachability 判斷的是「是否有網路路徑」,並不代表網路品質良好或伺服器可達——真正的連線狀態仍需以請求結果為準。
同步請求會阻塞當前執行緒,直到伺服器回應或逾時:
NSURL *url = [NSURL URLWithString:URL];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
非同步請求透過 delegate 回呼取得資料,不會阻斷主執行緒,因此是絕大多數情況的首選:
NSURL *url = [NSURL URLWithString:URL];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60];
[NSURLConnection connectionWithRequest:request delegate:self];
四個回呼方法的職責:
#pragma mark NSURLConnectionDataDelegate
// 1. 伺服器開始回應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_resultStr = [[NSMutableString alloc] init];
}
// 2. 收到部分資料(可能被呼叫多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[_resultStr appendString:str];
}
// 3. 全部接收完畢
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self result:[_resultStr substringWithRange:NSMakeRange(78, 1)]];
}
// 4. 失敗
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"error:%@", [error localizedDescription]);
}
didReceiveData: 會被呼叫多次,因此必須在 didReceiveResponse: 中初始化容器、在這裡累加,這也是為什麼範例使用 NSMutableString 而非 NSString。
GET 請求:參數直接接在 URL 後面。
NSString *pStr = self.textField.text;
NSString *strUrl = [@"https://webservice.webxml.com.cn/webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode="
stringByAppendingFormat:@"%@", pStr];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60];
[NSURLConnection connectionWithRequest:request delegate:self];
POST 請求:有四個關鍵差異。
// 差異一:URL 不帶參數
NSString *postStr1 = @"https://webservice.webxml.com.cn/webservices/qqOnlineWebService.asmx/qqCheckOnline";
NSURL *postUrl = [NSURL URLWithString:postStr1];
// 差異二:必須用 NSMutableURLRequest
NSMutableURLRequest *postRequest =
[NSMutableURLRequest requestWithURL:postUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60];
// 差異三:參數放進 body
NSString *postStr2 = [NSString stringWithFormat:@"qqCode=%@", self.textField.text];
NSData *postData = [postStr2 dataUsingEncoding:NSUTF8StringEncoding];
[postRequest setHTTPBody:postData];
// 差異四:必須明確指定方法為 POST
[postRequest setHTTPMethod:@"POST"];
[NSURLConnection connectionWithRequest:postRequest delegate:self];
兩者都使用非同步連線,因此共用同一組 delegate 回呼。
GET 的參數暴露在網址上,適合查詢類、無敏感資訊的請求;POST 的內容在 body 中,適合傳送較長資料或含敏感資訊的表單。但要注意:POST 並不等於加密,兩者若走 HTTP 都會是明文傳輸,涉及帳號、個資時務必改用 HTTPS。
另外,URL 中的中文或空白字元必須先做 percent encoding,否則 URLWithString: 會回傳 nil。實務上建議用 NSURLComponents 搭配 queryItems 來組裝 GET 參數,系統會自動處理編碼,能省下不少除錯時間。
最後,NSURLConnection 已被標記為 deprecated,新專案請改用 NSURLSession;UIAlertView 亦應替換為 UIAlertController。