您的位置:首页 > 理论基础 > 计算机网络

iPhone开发下载网络数据的几种方法总结

2013-01-18 12:14 549 查看
1
使用NSURLConnection的同步方法下载

view
source

print?

01.
NSString
*urlAsString = @
"http://www.jouhu.com/json/info.zip"
;---要下载的全路径名


02.
NSURL
*url = [NSURL URLWithString:urlAsString];


03.
NSURLRequest
*request = [NSURLRequest requestWithURL:url];


04.
NSError
*error = nil;


05.


06.
NSData
*data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];


07.
/*下载的数据*/


08.
if
(data!=nil)
{


09.
NSLog(@
"下载成功"
);


10.
if
([data
writeToFile:@
"/Users/sunningning/Desktop/activation.zip"
atomically:YES])
{--下载到目的路径名


11.
NSLog(@
"保存成功!"
);


12.
}


13.
else


14.
{


15.
NSLog(@
"保存失败!"
);


16.
}


17.
}


18.
else
{


19.
NSLog(@
"%@"
,error);


20.
}


2 使用NSURLConnection的异步方法下载

view
source

print?

01.
NSString
*urlAsString = @
"http://www.apple.com"
;


02.
NSURL
*url = [NSURL URLWithString:urlAsString];


03.
NSURLRequest
*urlRequest = [NSURLRequest requestWithURL:url];


04.
NSOperationQueue
*queue = [[NSOperationQueue alloc] init];


05.


06.
[NSURLConnection
sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error)


07.
{


08.
if
([data
length] >
0
&&
error == nil){


09.
NSString
*html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];


10.
NSLog(@
"HTML
= %@"
,
html); }


11.


12.
else
if
([data
length] ==
0
&&
error == nil){


13.
NSLog(@
"Nothing
was downloaded."
);


14.
}


15.


16.
else
if
(error
!= nil){


17.
NSLog(@
"Error
happened = %@"
,
error); }


18.
}];


3 使用NSURLConnection的异步+GCD的方法下载

view
source

print?

01.
+
(
void
)performRequestWithUri:(NSString
*)requestUri params:(NSDictionary *)params completionHandler:(
void
(^)(NSDictionary
*, NSError *))completionBlock


02.
{


03.


04.
//
Generate the URL


05.
NSString
*requestUrl = [NSString stringWithFormat:@
"http://the.api.com%@"
,
requestUri];


06.


07.
//
Create the connection


08.
NSURLRequest
*request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:requestUrl]];


09.


10.
//
Make an NSOperationQueue


11.
NSOperationQueue
*queue = [[NSOperationQueue alloc] init];


12.
[queue
setName:@
"com.your.unique.queue.name"
];


13.


14.
//
Send an asyncronous request on the queue


15.
[NSURLConnection
sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {


16.


17.
//
If there was an error getting the data


18.
if
(error)
{


19.


20.
dispatch_async(dispatch_get_main_queue(),
^(
void
)
{


21.
completionBlock(nil,
error);


22.
});


23.
return
;


24.
}


25.


26.
//
Decode the data


27.
NSError
*jsonError;


28.
NSDictionary
*responseDict = [NSJSONSerialization JSONObjectWithData:data options:
0
error:&jsonError];


29.


30.
//
If there was an error decoding the JSON


31.
if
(jsonError)
{


32.


33.
dispatch_async(dispatch_get_main_queue(),
^(
void
)
{


34.


35.
});


36.
return
;


37.
}


38.


39.
//
All looks fine, lets call the completion block with the response data


40.
dispatch_async(dispatch_get_main_queue(),
^(
void
)
{


41.
completionBlock(responseDict,
nil);


42.
});


43.
}];


44.
}


具体调用方法:

view
source

print?

1.
[SHAPIController
performRequestWithUri:@
"http://www.jouhu.com/json/info.php"
params:nil
completionHandler:^(NSDictionary *response, NSError *error) {


2.


3.
if
(error)
{


4.
NSLog(@
"%@"
,
error);


5.
}


6.


7.
NSLog(@
"%@"
,
response);


8.
}];


返回的数据根据我们而定.

4 实现delegate的方法实现异步

view
source

print?

01.
NSURLConnection
*conn= [[NSURLConnection alloc]


02.
initWithRequest:theRequest
delegate:self];


03.
[conn
start];


04.
if
(conn)


05.
{


06.
NSLog(@
"Connection
Successful"
);


07.
}


08.
else


09.
{


10.
NSLog(@
"Connection
could not be made"
);


11.
}


12.
}


view
source

print?

01.
-
(
void
)connection:(NSURLConnection
*)connection didReceiveResponse:(NSURLResponse *)theResponse {


02.
self.response
= theResponse;


03.
[data
setLength:
0
];
//
reset data


04.
}


05.


06.
-
(
void
)connection:(NSURLConnection
*)connection didReceiveData:(NSData *)theData {


07.
[data
appendData:theData];
//
append incoming data


08.
}


09.


10.
-
(
void
)connection:(NSURLConnection
*)connection didFailWithError:(NSError *)error {


11.
[UIApplication
sharedApplication].networkActivityIndicatorVisible = NO;


12.
self.data
= nil;


13.
if
(handler)
{ [queue addOperationWithBlock:^{ handler(response, nil, error); }];}


14.
}


15.


16.
-
(
void
)connectionDidFinishLoading:(NSURLConnection
*)connection {


17.
[UIApplication
sharedApplication].networkActivityIndicatorVisible = NO;


18.
//
TODO: Are we passing the arguments to the block correctly? Should we copy them?


19.
handleData(self.data);
//处理数据,需要定义方法


20.
}


我们自身的应用采用的是最后一种方法,对于很多图片更新的,可以采取第三种方法,第一种方法是同步数据下载,容易造成UI阻塞。需要注意。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐