@@ -48,6 +48,20 @@ - (NSCachedURLResponse *)connection:(NSURLConnection *)connection
4848}
4949
5050- (void )connection : (NSURLConnection *)connection didReceiveResponse : (NSURLResponse *)response {
51+ if ([response isKindOfClass: [NSHTTPURLResponse class ]]) {
52+ NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode ];
53+ if (statusCode >= 400 ) {
54+ [self .outputFileStream close ];
55+ [connection cancel ];
56+
57+ NSError *err = [NSError errorWithDomain: @" http download error"
58+ code: statusCode
59+ userInfo: nil ];
60+ self.failCallback (err);
61+ return ;
62+ }
63+ }
64+
5165 self.expectedContentLength = response.expectedContentLength ;
5266 [self .outputFileStream open ];
5367}
@@ -98,13 +112,24 @@ - (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
98112}
99113
100114- (void )connectionDidFinishLoading : (NSURLConnection *)connection {
115+ [self .outputFileStream close ];
116+
117+ // MUST have received bytes from remote server. do not do this, we will get a 0 bytes file of download.zip in download directory,
118+ // the variable isZip is FALSE and download.zip will be renamed app.bundle that occurring by self.doneCallback(isZip) method.
119+ if (self.receivedContentLength < 1 ) {
120+ NSError *err = [NSError errorWithDomain: @" received nothing"
121+ code: -1
122+ userInfo: nil ];
123+ self.failCallback (err);
124+ return ;
125+ }
126+
101127 // expectedContentLength might be -1 when NSURLConnection don't know the length(e.g. response encode with gzip)
102128 if (self.expectedContentLength > 0 ) {
103129 // We should have received all of the bytes if this is called.
104130 assert (self.receivedContentLength == self.expectedContentLength );
105131 }
106132
107- [self .outputFileStream close ];
108133 BOOL isZip = _header[0 ] == ' P' && _header[1 ] == ' K' && _header[2 ] == 3 && _header[3 ] == 4 ;
109134 self.doneCallback (isZip);
110135}
0 commit comments