溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

[IOS]網(wǎng)絡(luò)操作+圖片的下載和讀取+json數(shù)據(jù)讀取

發(fā)布時間:2020-06-11 11:04:03 來源:網(wǎng)絡(luò) 閱讀:586 作者:蓬萊仙羽 欄目:移動開發(fā)

如何讀取沙盒中的文件,和保存網(wǎng)絡(luò)資源到沙盒中?

-(NSString *)dataFilePath:(NSString*)fileName

{

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    

    NSString *document=[paths objectAtIndex:0];

    

    return [documentstringByAppendingPathComponent:fileName];

}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection

    //可以下載圖片

    [self.datawriteToFile:[selfdataFilePath:@"image.jpg"]atomically:YES];

    self.webView.hidden =YES;

    //將沙盒中的圖片加載到界面中

    NSString *path = [selfdataFilePath:@"image.jpg"];

    UIImage *imag = [[UIImagealloc]initWithContentsOfFile:path];

    UIImageView *img = [[UIImageViewalloc]initWithImage:imag];

    CGRect rect = CGRectMake(0,0,320,460);

    img.frame = rect;

    [self.viewaddSubview:img];

}


進入主題,接下來我要實現(xiàn)三個功能:

1.訪問網(wǎng)頁

2.從網(wǎng)上加載圖片資源到本地

3.發(fā)送get請求獲取到天氣預(yù)報的接口,然后保存到本地接著是json解析

功能設(shè)計:

1.webView的使用

PageViewController.h:

#import <UIKit/UIKit.h>  @interface PageViewController : UIViewController<UIWebViewDelegate> @property (retain, nonatomic) IBOutlet UIWebView *webView; - (IBAction)GoClick:(id)sender; @property (retain, nonatomic) IBOutlet UITextField *txtUrl; - (IBAction)resignBoardClick:(id)sender; @property(retain,nonatomic)NSURL *url; @property(nonatomic,retain)UIAlertView *alert; @end

PageViewController.m:

// //  PageViewController.m //  地圖+網(wǎng)絡(luò) // //  Created by 丁小未 on 13-8-27. //  Copyright (c) 2013年 dingxiaowei. All rights reserved. //  #import "PageViewController.h"  @interface PageViewController ()  @end  @implementation PageViewController  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];     if (self) {         self.title = @"頁面";     }     return self; }  -(void)pageLoad1:(NSURL *)url {     NSURLRequest *request = [NSURLRequest requestWithURL:url];     [self.webView loadRequest:request]; }  - (void)viewDidLoad {     [super viewDidLoad];     self.url = [NSURL URLWithString:@"http://www.baidu.com"];     NSURLRequest *request = [NSURLRequest requestWithURL:self.url];     [self pageLoad1:self.url];  }  -(void)webViewDidFinishLoad:(UIWebView *)webView {     [self.alert dismissWithClickedButtonIndex:0 animated:YES]; }  -(void)webViewDidStartLoad:(UIWebView *)webView {     self.alert = [[UIAlertView alloc] initWithTitle:@"Loading..." message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];     [self.alert show];          UIActivityIndicatorView *aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];     aiv.center = CGPointMake(self.alert.bounds.size.width/2, self.alert.bounds.size.height/2);     [aiv startAnimating];     [self.alert addSubview:aiv]; }  - (void)dealloc {     [_webView release];     [_url release];     [_txtUrl release];     [_alert release];     [super dealloc]; } - (IBAction)GoClick:(id)sender {     [self.txtUrl resignFirstResponder];     if (self.txtUrl.text != nil) {         self.url = [NSURL URLWithString:self.txtUrl.text];         [self pageLoad1:self.url];     }     else     {         self.alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"地址不能為空" delegate:self cancelButtonTitle:@"OK"otherButtonTitles: nil];         [self.alert show];     } } - (IBAction)resignBoardClick:(id)sender {     [self.txtUrl resignFirstResponder]; } @end 

xib:

[IOS]網(wǎng)絡(luò)操作+圖片的下載和讀取+json數(shù)據(jù)讀取

效果圖:

請求網(wǎng)絡(luò)的加載效果:

[IOS]網(wǎng)絡(luò)操作+圖片的下載和讀取+json數(shù)據(jù)讀取

請求結(jié)束的效果圖:

[IOS]網(wǎng)絡(luò)操作+圖片的下載和讀取+json數(shù)據(jù)讀取

2.根據(jù)URL地址請求網(wǎng)絡(luò)圖片并且顯示出來

PicViewController.h:

// //  PicViewController.h //  地圖+網(wǎng)絡(luò) // //  Created by 丁小未 on 13-8-27. //  Copyright (c) 2013年 dingxiaowei. All rights reserved. //  #import <UIKit/UIKit.h>  @interface PicViewController : UIViewController<UIWebViewDelegate,NSURLConnectionDataDelegate>  @property(nonatomic,retain)NSURL *url; @property (retain, nonatomic) IBOutlet UIWebView *webView; @property (retain, nonatomic) NSMutableData * data; @property (retain, nonatomic) NSURLConnection * connection;  @end 

PicViewController.m:

// //  PicViewController.m //  地圖+網(wǎng)絡(luò) // //  Created by 丁小未 on 13-8-27. //  Copyright (c) 2013年 dingxiaowei. All rights reserved. //  #import "PicViewController.h"  @interface PicViewController ()  @end  @implementation PicViewController  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];     if (self) {         // Custom initialization     }     return self; }  - (void)viewDidLoad {     [super viewDidLoad];     NSString *urlString =@"http://e.hiphotos.baidu.com/album/w%3D2048/sign=76d548844afbfbeddc59317f4cc8f636/267f9e2f07082838334a05afb999a9014d08f1c2.jpg";     self.url = [NSURL URLWithString:urlString];     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:self.url];     [self.webView loadRequest:request];          //step3:創(chuàng)建鏈接          self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];          if(self.connection)              {                  NSLog(@"創(chuàng)建鏈接成功");              }else{                  NSLog(@"創(chuàng)建鏈接失敗");              }               [urlString release]; }  //獲取數(shù)據(jù)  -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  {               NSMutableData * data = [[NSMutableData alloc] init];          self.data = data;          [data release];      }  //不斷的獲取數(shù)據(jù)  -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  {          //接受返回數(shù)據(jù),這個方法可能會被調(diào)用多次,因此將多次返回數(shù)據(jù)加起來          NSInteger datalength = [data length];          NSLog(@"返回數(shù)據(jù)量:%d",datalength);          [self.data appendData:data];      }  //獲取文件地址  -(NSString *)dataFilePath:(NSString*)fileName  {          NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);          NSString *document=[paths objectAtIndex:0];          return [document stringByAppendingPathComponent:fileName];      }  -(void)connectionDidFinishLoading:(NSURLConnection *)connection  {      //可以下載圖片     [self.data writeToFile:[self dataFilePath:@"image.jpg"] atomically:YES];     self.webView.hidden = YES;     //將沙盒中的圖片加載到界面中     NSString *path = [self dataFilePath:@"image.jpg"];     UIImage *imag = [[UIImage alloc] initWithContentsOfFile:path];     UIImageView *img = [[UIImageView alloc] initWithImage:imag];     CGRect rect = CGRectMake(0, 0, 320,460);     img.frame = rect;     [self.view addSubview:img]; }   -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error  {          NSLog(@"連接失敗");      }  - (void)dealloc {     [_webView release];     [super dealloc]; } @end 


xib:

[IOS]網(wǎng)絡(luò)操作+圖片的下載和讀取+json數(shù)據(jù)讀取

請求后的效果圖:

[IOS]網(wǎng)絡(luò)操作+圖片的下載和讀取+json數(shù)據(jù)讀取

3.請求天氣預(yù)報的接口然后json解析請求后的數(shù)據(jù)并且保存到本地顯示出來

WeatherViewController.h:

// //  WeatherViewController.h //  地圖+網(wǎng)絡(luò) // //  Created by 丁小未 on 13-8-27. //  Copyright (c) 2013年 dingxiaowei. All rights reserved. //  #import <UIKit/UIKit.h>  @interface WeatherViewController : UIViewController<UIWebViewDelegate,NSURLConnectionDataDelegate> @property (retain, nonatomic) IBOutlet UITextField *txtCity; @property (retain, nonatomic) IBOutlet UITextField *txtMaxTem; @property (retain, nonatomic) IBOutlet UITextField *txtMinTem; @property (retain, nonatomic) IBOutlet UITextField *txtTempreture; @property(retain,nonatomic)NSMutableData *data; @property (retain, nonatomic) IBOutlet UILabel *label; @property(retain,nonatomic)NSURLConnection *connection; - (IBAction)resignBoard:(id)sender;  @end 

WeatherViewController.m:

// //  WeatherViewController.m //  地圖+網(wǎng)絡(luò) // //  Created by 丁小未 on 13-8-27. //  Copyright (c) 2013年 dingxiaowei. All rights reserved. //  #import "WeatherViewController.h"  @interface WeatherViewController ()  @end  @implementation WeatherViewController  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];     if (self) {              }     return self; }  - (void)viewDidLoad {     [super viewDidLoad];     self.label.text = @"正在請求數(shù)據(jù)";     NSString *urlString = @"http://www.weather.com.cn/data/cityinfo/101020100.html";     NSURL *url = [NSURL URLWithString:urlString];     //實例化一個request     NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];     //創(chuàng)建連接     self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];     if (self.connection) {         NSLog(@"創(chuàng)建連接成功");     }     else     {         NSLog(@"創(chuàng)建連接失敗");     }     [url release];     [urlString release]; }  //獲取數(shù)據(jù)  -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  {          //接受一個服務(wù)端回話,再次一般初始化接受數(shù)據(jù)的對象          //NSLog(@"返回數(shù)據(jù)類型%@",[response ]);          //NSLog(@"返回數(shù)據(jù)編碼%@",[response text]);          NSMutableData * data = [[NSMutableData alloc] init];          self.data = data;          [data release];      }  //不斷的獲取數(shù)據(jù)  -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  {          //接受返回數(shù)據(jù),這個方法可能會被調(diào)用多次,因此將多次返回數(shù)據(jù)加起來          NSInteger datalength = [data length];          NSLog(@"返回數(shù)據(jù)量:%d",datalength);          [self.data appendData:data];      }  //獲取文件地址  -(NSString *)dataFilePath:(NSString*)fileName  {          NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);          NSString *document=[paths objectAtIndex:0];          return [document stringByAppendingPathComponent:fileName];      }   -(void)connectionDidFinishLoading:(NSURLConnection *)connection  {         //連接結(jié)束          NSLog(@"%d",[self.data length]);          self.label.text =@"天氣預(yù)報";          //可以下載圖片          //[self.data writeToFile:[self dataFilePath:@"image.jpg"] atomically:YES];                //    NSString * mystr = [[NSStringalloc] initWithData:self.dataencoding:NSUTF8StringEncoding]; //     //    [mystr writeToFile:[selfdataFilePath:@"百度圖片—全球最大中文圖片庫.html"] atomically:YES encoding:NSUTF8StringEncoding error:nil]; //     //    NSLog(@"最后的結(jié)果%@",mystr); //     //    [mystr release];              NSDictionary *weather = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers  error:nil];              NSLog(@"%@",weather);              [weather writeToFile:[self dataFilePath:@"weather.plist"] atomically:YES];          NSLog(@"%@",[weather allKeys]);     NSDictionary *dic = [weather objectForKey:@"weatherinfo"];     NSLog(@"%@",dic);          self.txtCity.text = [dic objectForKey:@"city"];     self.txtTempreture.text = [dic objectForKey:@"weather"];     self.txtMaxTem.text = [dic objectForKey:@"temp2"];     self.txtMinTem.text = [dic objectForKey:@"temp1"]; }   -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error  {          self.label.text =@"連接失敗";      }  - (void)dealloc {     [_txtCity release];     [_txtMaxTem release];     [_txtMinTem release];     [_txtTempreture release];     [_label release];     [super dealloc]; } - (IBAction)resignBoard:(id)sender {     [self.txtMaxTem resignFirstResponder];     [self.txtMinTem resignFirstResponder];     [self.txtCity resignFirstResponder];     [self.txtTempreture resignFirstResponder]; } @end 

xib:

[IOS]網(wǎng)絡(luò)操作+圖片的下載和讀取+json數(shù)據(jù)讀取

請求網(wǎng)絡(luò)后的效果圖:

[IOS]網(wǎng)絡(luò)操作+圖片的下載和讀取+json數(shù)據(jù)讀取

Demo源文件下載(猛戳)

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

j
AI