iOS - NSURLConnection - Check for URL - ios

I'm using NSURLConnection with sendAsynchronousRequest method (and handing the data in block).
Using above method, I'm downloading a video file from server and saving locally in cache folder.
This is working fine if the URL is valid. If the URL is invalid (that is the video is not available at given URL), it is still saving a file with the file name that I'm giving. NSError is nil and NSData object is not nil. How can I check whether the URL is valid or catch the error if URL is not there?

Check the NSURLResponse in the block, if it is an http request it is really an NSHTTPURLResponse. Check the statusCode to see the HTTP error. It may be a 404, 302, etc.
Also check the returned data, convert it to a string and see if there is anything interesting there. Sometimes there is a redirect in the returned html.

Related

Alamofire: Download request saves error response as original file even when validation fails

I use Alamofire 4.5.1 to download some mp3 files.
If I provide incorrect URL or the request can't be authorised I get an error with 4xx status code (as it is supposed to be) and in my particular case xml with the error explanation.
The issue is that Alamofire saves the error xml response to my destination url, which looks like: .../my-sound-file.mp3
In other place in my app, which is decoupled from downloading code, I might later check if I have .../my-sound-file.mp3 on disk and try to play it, which obviously fails since my sound file is actually xml file with mp3 extension.
Is there a nicer way to prevent Alamofire saving an error data as an originally requested file?
The code I use (with my crude solution to this issue):
let destination: DownloadRequest.DownloadFileDestination = ...
let request = self.sessionManager.download(url, to: destination)
request.validate()
request.response { response in
if response.error == nil {
// do some stuff
} else {
// So far I am forced to manually remove file in case of error
try? FileManager.default.removeItem(at: destURL)
// propagate error
}
}
I stumbled upon this because I assumed that if a request validation fails the destination URL should be empty.
I think I am not the only one with this assumption: Alamofire: file download and validation failure
Personally, I delete the file in case of error. Just as you propose.

What is Mediafire expecting on upload request

I'm attempting to upload a file using Mediafire's API. Its not clear to me what they expect in the body of the message. I'm attempting to follow the API described in https://www.mediafire.com/developers/upload.php#upload
My understanding is that some parameters are passed in a query string as part of the URL. I'm passing the session_token on the URL.
I set an HTTP header for the file size, x-filesize.
I'm setting the method to POST and sending to base url (before the query string) http://www.mediafire.com/api/upload/upload.php
Its not clear to me what should be in the body. I tried including the pure data from the file being uploaded. I've also tried adding more data to make it look like multipart form.
In either case I'm getting no response at all from the server. I'm doing this in objective-c on a Mac. The NSURLConnection request comes back with nil response and nil error. I'm using
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
The Mediafire upload API is expecting parameters to be send in the URL as the query string, GET style.
The data from the file is included in the body as a multipart form. If the body is improperly constructed, Mediafire may not return a relevant error.
Headers specified in the API are sent as headers in the body.
The 'path' parameter only appears to be honored if a uploadkey is also provided. No error is provided indicating if the path parameter was honored.
Maximum file size appears to be around 4MB.

RESTKit response.url changed order of parameters

I'm using RESTKit to get data from a rest-api.
This is the URL i set for my request, here's the log just before the request goes off.
2014-04-03 15:51:10.186 xxx[35745:60b] Just sent URL: /api/dspObjGetNewsList?action=coverage&count=30&start=0&open=0&user=xxx&unique=36027&type=all&country=Sweden,global&division=Strategic Industries,Regional Sales and Service,Automotive
Then i log the reponse URL.
- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response {
NSLog(#"xxx: %d, url: %#", [response statusCode], response.URL);
And i get this?
xxx: response code: 200, url: url/api/dspObjGetNewsList?unique=26791&type=all&division=Strategic%20Industries%2CRegional%20Sales%20and%20Service%2CAutomotive&user=xxx&action=coverage&open=0&country=Sweden%2Cglobal&count=30&start=0
Why am i getting a different URL in my response? Does RESTKit modify my url?
Have you configured HTTPClient properly? Use - (id)initWithHTTPClient:(AFHTTPClient *)client method to configure HTTPClient. For instance:
AFHTTPClient *HTTPClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"www.url.com"]];
Your first log appears to be a raw string of the URL. The second log appears to be the % escaped URL version of that string. This isn't a RestKit thing, it's a URL loading system thing. Certain characters need to be escaped so that they are valid for use in a URL.
For example, your original string has a number of spaces in it. This isn't allowed in a URL and each must be changed to %20.
Why the parameters change order isn't clear - it depends on how you created the string and supplied the parameters to RestKit. But, the order doesn't matter to the processing so you shouldn't need to worry about it.

iOS url response bool

net web service that returns true or false but i don't know how to catch that response in my IOS App.
My service updates data in a database and i know it works the data gets updated it's catch the response that is the problem, i like to know so i can tell the user if something went wrong.
For those of you that know c# its a bool method, just simple try catch and return true or false.
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//What to write here to catch my true or false
if(response) {
//true
} else {
//false
}
}
Thank you for your help
You should implementconnection:didReceiveData: to get and save NSData and – connectionDidFinishLoading: where you can interpret received data as BOOL.
basically didReceiveResponse: only get to you know about server response to your request not the entire answer.
You should check the response's HTTP status code, e.g.:
NSInteger statusCode = [(NSHTTPURLResponse*)response statusCode];
The status code for a successful request uses the range [200..299].
For example a successful GET request would be indicated with a 200 (OK).
A successful POST request will be indicated with a 201 (Created).
A successful DELET request will be indicated with a 204 (No Content)..
See also: wiki List of HTTP status codes.
Furthermore, you need to check the kind of data the server sent to you:
NSString* mimeType = [response MIMEType];
The mime type has been sent by the server in the Content-Type header of the response.
See also wiki MIME Internet Media Type
What you actually get fully depends on your request AND the server.
For example, the server may always answer with a JSON as content type. In this case, the header Content-Type of the response would be application/json. The actual JSON which represents the answer, will be related to the status code as well.
In order to provide a nice human readable message to the user, you need to consult the web service API and figure out how it is specified. Certain web service APIs may have a considerable large API. Unfortunately, some web services lack a comprehensive documentation.

ASIHTTPRequest download is writing JSON error to zip

I have a method for downloading a file as file_name.zip to the documents directory. However, if I receive an error, such as 'file does not exist', the library is writing the JSON payload to file_name.zip.
How do we check for JSON error in requestFinished:?
responseString or responseData is always null.
You probably want to check the request.responseStatusCode and check against a 404 error. But honestly you should look into AFNetworking. ASIHTTPRequest is no longer supported and AFNetworking has success/failure blocks.

Resources