IOS開發之網路開發工具

來源:互聯網
上載者:User

IOS開發之網路開發工具

IOS開發之網路開發工具

做移動端開發 經常會涉及到幾個模組:1、網路檢測 2、網路請求get和post請求 3、檔案上傳 4、檔案下載 5、斷點續傳

現在將這些一一分享給大家 ,也歡迎大家一起學習和討論 本例子採用AFNetWorking架構

網路檢測:


#pragma mark - Reachability Management (iOS 6-7)


//網路監聽(用於檢測網路是否可以連結。此方法最好放於AppDelegate中,可以使程式開啟便開始檢測網路)
- (void)reachabilityManager
{
//開啟網路監聽
[manager.reachabilityManager startMonitoring];

//監聽網路變化
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {

//當網路不可用(無網路或請求延時)
case AFNetworkReachabilityStatusNotReachable:
break;

//當為手機蜂窩資料網和WiFi時
case AFNetworkReachabilityStatusReachableViaWiFi:
case AFNetworkReachabilityStatusReachableViaWWAN:
break;

//其它情況
default:
break;
}
}];

//停止網路監聽(若需要一直檢測網路狀態,可以不停止,使其一直運行)
[manager.reachabilityManager stopMonitoring];
}


Get請求資料:

#pragma mark - GET Request (iOS 6-7)


//GET請求
- (void)methodGet
{
//致空請求
if (manager) {
manager = nil;
}

//建立請求
manager = [AFHTTPRequestOperationManager manager];

//佈建要求的解析器為AFHTTPResponseSerializer(用於直接解析資料NSData),預設為AFJSONResponseSerializer(用於解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//發送GET請求
[manager GET:@"介面地址" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

//請求成功(當解析器為AFJSONResponseSerializer時)
NSLog(@"Success: %@", responseObject);

//請求成功(當解析器為AFHTTPResponseSerializer時)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

//請求失敗
NSLog(@"Error: %@", error);
}];

}

POST請求:

#pragma mark - POST Request (iOS 6-7)


//POST請求
- (void)methodPost
{
//致空請求
if (manager) {
manager = nil;
}

//添加參數
NSDictionary *parameters = @{@"Key": @"Object",
@"Key": @"Object"};

//建立請求
manager = [AFHTTPRequestOperationManager manager];

//佈建要求的解析器為AFHTTPResponseSerializer(用於直接解析資料NSData),預設為AFJSONResponseSerializer(用於解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//發送POST請求
[manager POST:@"介面地址" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

//請求成功(當解析器為AFJSONResponseSerializer時)
NSLog(@"Success: %@", responseObject);

//請求成功(當解析器為AFHTTPResponseSerializer時)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

//請求失敗
NSLog(@"Error: %@", error);
}];
}

上傳:
#pragma mark - Upload Request (iOS 6-7)


//上傳(以表單方式上傳,以圖片為例)
- (void)methodUpload
{
//致空請求
if (manager) {
manager = nil;
}

//添加參數
NSDictionary *parameters = @{@"Key": @"Object",
@"Key": @"Object"};

//建立請求
manager = [AFHTTPRequestOperationManager manager];

//佈建要求的解析器為AFHTTPResponseSerializer(用於直接解析資料NSData),預設為AFJSONResponseSerializer(用於解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//發送POST請求,添加需要發送的檔案,此處為圖片
[manager POST:@"介面地址" parameters:parameters constructingBodyWithBlock:^(id formData) {

//添加圖片,並對其進行壓縮(0.0為最大壓縮率,1.0為最小壓縮率)
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"圖片名字(注意尾碼名)"], 1.0);

//添加要上傳的檔案,此處為圖片
[formData appendPartWithFileData:imageData name:@"伺服器放圖片的參數名(Key)" fileName:@"圖片名字" mimeType:@"檔案類型(此處為圖片格式,如image/jpeg)"];

} success:^(AFHTTPRequestOperation *operation, id responseObject) {

//請求成功(當解析器為AFJSONResponseSerializer時)
NSLog(@"Success: %@", responseObject);

//請求成功(當解析器為AFHTTPResponseSerializer時)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

//請求失敗
NSLog(@"Error: %@", error);
}];

}

下載:

#pragma mark - Download Request (iOS 6-7)


//下載
- (void)methodDownload
{
//下載進度條
UIProgressView *downProgressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
downProgressView.center = CGPointMake(self.view.center.x, 220);
downProgressView.progress = 0;
downProgressView.progressTintColor = [UIColor blueColor];
downProgressView.trackTintColor = [UIColor grayColor];
[self.view addSubview:downProgressView];

//設定存放檔案的位置(此Demo把檔案儲存在iPhone沙箱中的Documents檔案夾中。關於如何擷取檔案路徑,請自行搜尋相關資料)
//方法一
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *cachesDirectory = [paths objectAtIndex:0];
// NSString *filePath = [cachesDirectory stringByAppendingPathComponent:@"檔案名稱"];
//方法二
NSString *filePath = [NSString stringWithFormat:@"%@/Documents/檔案名稱(注意尾碼名)", NSHomeDirectory()];

//列印檔案儲存的路徑
NSLog(@"%@",filePath);

//建立要求管理
operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];

//添加下載請求(擷取伺服器的輸出資料流)
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];

//設定下載進度條
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

//顯示下載進度
CGFloat progress = ((float)totalBytesRead) / totalBytesExpectedToRead;
[downProgressView setProgress:progress animated:YES];
}];

//要求管理判斷請求結果
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

//請求成功
NSLog(@"Finish and Download to: %@", filePath);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

//請求失敗
NSLog(@"Error: %@",error);
}];

}

斷點續傳:

#pragma mark - Download Management (iOS 6-7)


//開始下載(斷點續傳)
- (void)downloadStart
{
[self methodDownload];
[operation start];
}


//暫停下載(斷點續傳)
- (void)downloadPause
{
[operation pause];
}


//繼續下載(斷點續傳)
- (void)downloadResume
{
[operation resume];

}

IOS7特性特有上傳和下載:



#pragma mark - Upload Request (iOS 7 only)


//上傳(iOS7專用)
- (void)methodUploadFor7
{
//致空請求
if (sessionManager) {
sessionManager = nil;
}

//建立請求(iOS7專用)
sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

//添加請求介面
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"上傳地址"]];

//添加上傳的檔案
NSURL *filePath = [NSURL fileURLWithPath:@"本地檔案地址"];

//發送上傳請求
NSURLSessionUploadTask *uploadTask = [sessionManager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {

//請求失敗
NSLog(@"Error: %@", error);

} else {

//請求成功
NSLog(@"Success: %@ %@", response, responseObject);
}
}];

//開始上傳
[uploadTask resume];
}


#pragma mark - Download Request (iOS 7 only)


//下載(iOS7專用)
- (void)methodDownloadFor7
{
//致空請求
if (sessionManager) {
sessionManager = nil;
}

//建立請求(iOS7專用)
sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

//添加請求介面
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];

//發送下載請求
NSURLSessionDownloadTask *downloadTask = [sessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

//設定存放檔案的位置(此Demo把檔案儲存在iPhone沙箱中的Documents檔案夾中。關於如何擷取檔案路徑,請自行搜尋相關資料)
NSURL *filePath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];

return [filePath URLByAppendingPathComponent:[response suggestedFilename]];

} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

//下載完成
NSLog(@"Finish and Download to: %@", filePath);
}];

//開始下載
[downloadTask resume];

}

源碼:http://download.csdn.net/detail/wangliang198901/7935199




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.