NSString constants for NSURLRequest HTTPMethod property? - ios

Does Foundation have NSString constants for the supported HTTPMethod values (eg for GET, POST, etc)?
Searched the NSURLRequest docs, but couldn't find anything.

To my knowledge, NSURLRequest doesn't have any constants for HTTP method types. You could, however, define your own and use them elsewhere. Something like this:
//Somewhere
#define setPOST(request) [request setHTTPMethod:#"GET"]
//...later in code
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
setPOST(request);
I would also highly recommend using AFNetworking. With that library, you can easily do things like:
[connectionMgr POST:url parameters:submitDict success:nil failure:nil]; //Obviously bare-bones, you'd need to fill in the parameters and blocks

Related

Unable to add a header to NSMutableRequest

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:tempURL]] autorelease];
[request setValue:encryptedValue forHTTPHeaderField:#"EncString"];
I could spot all other headers in the request but this specific header is missing, can any one let me know what could be the reasons.
I have tried the following code:
NSString *tempURL = #"https://stackoverflow.com/questions/50701101/unable-to-add-a-header-to-nsmutablerequest";
NSString *encryptedValue = #"whatever_that_has_no_special_characters_or_values_that_would_make_you_think_it_is_relevant_to_reproduce_this_issue";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:tempURL]];
[request setValue:encryptedValue forHTTPHeaderField:#"EncString"];
NSLog(#"%#", request.allHTTPHeaderFields);
The output is:
{
EncString = "whatever_that_has_no_special_characters_or_values_that_would_make_you_think_it_is_relevant_to_reproduce_this_issue";
}
which looks good. There is no reason to suspect the code you provided is responsible for the issue. Maybe you should check one of the following:
Is encryptedValue truly a valid object to be placed into header (is string, not too long, no very special characters)
Is the object you are printing really this specific request (printing NSLog(#"%p", request); returns same result)
In no place in this object a herder is being removed (if nothing else subclass NSMutableURLRequest and override relevant methods to track what is going on)
If none of these work create a post with additional details on what you have done, where are you checking these headers and "could spot all other headers".

iOS 10 get file size before download

I need to get file size from url to decide whether i will download it or not. I tried it with NSMutableURLRequest but in the delegate, it returns -1 always. And the NSMutableURLRequest method is deprecated now. I added all the delegate (NSURLConnectionDelegate,NSURLConnectionDownloadDelegate,NSURLConnectionDataDelegate) in .h file but it does not work. My code is :
NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://download.quranicaudio.com/quran/abdullaah_3awwaad_al-juhaynee/001.mp3"]];
[req setHTTPMethod:#"Head"];
NSURLConnection * con = [[NSURLConnection alloc] initWithRequest:req
delegate:self];
[con start];
[con release];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse (%lld) ", response.expectedContentLength);
}
Already tried with : How to find size of a file before downloading it in iOS 7?
Any solution for iOS 10+ ?
If you run the code after commenting [con release] it gives the exact size of your file.
Don't use NSURLConnection, instead use NSURLSession along with the NSURLSessionDownloadTask in your case. You can get the downloading file length by using property 'countOfBytesExpectedToReceive' of NSURLSessionTask which is the super class of NSURLSessionDownloadTask. There are various beautiful libraries available for networking. You can use AFNetworking for example. Or you can write your own code. Here are some links may be useful to you:
http://sweettutos.com/2014/09/16/how-you-would-use-nsurlsession-to-download-files/
https://www.infragistics.com/community/blogs/stevez/archive/2014/05/21/ios-objective-c-downloading-data-using-nsurlsession.aspx
PS: You can handle your requirements at a more granular level by using NSURLSessionDelegate methods for download task.

Add query string to all requests of NSURLSession

How to add query string to every url request of NSURLSession. All request will have the same query string.
How to append this?
Below is the way to send the string to every request URL
NSString *stringURL=[NSString stringWithFormat:#"%#%#%#",baseUrl,#"/API/URL/",your parameter];
// Allocate and initialize an NSURLConnection with the given request and delegate. The asynchronous URL load process is started as part of this method.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:stringURL] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:300];

NSURLCacheStorageNotAllowed still caching for NSURLRequest

I am working on an iPhone app project now which implements some connections using NSURLRequests using cachePolicy:NSURLCacheStorageNotAllowed (I am using ios 7).
But it seems like the responses are still cached and I get old responses for the same URL call. In spite of having the cache policy as "cachePolicy:NSURLCacheStorageNotAllowed".
Why is it still caching the responses? Is the issue still present in the latest release?
The correct enum for the cache Policy iOS7 is as described below:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:downloadURL
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
If you are over 3G, some provider use caching even if you disable it in your NSMutableURLRequest, so if the cache policy doesn't work then set the http header field cache-control to no-cache.
[request setValue:#"no-cache" forHTTPHeaderField:#"cache-control"];
Here the enum list check your header NSURLRequest.h for the correct up to date enum :)
enum
{
NSURLRequestUseProtocolCachePolicy = 0,
NSURLRequestReloadIgnoringLocalCacheData = 1,
NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, // Unimplemented
NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,
NSURLRequestReturnCacheDataElseLoad = 2,
NSURLRequestReturnCacheDataDontLoad = 3,
NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented
};
typedef NSUInteger NSURLRequestCachePolicy;
The correct answer for a non cached request should be NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:downloadURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; since NSURLRequestReloadIgnoringLocalAndRemoteCacheData it's unimplemented.
From https://developer.apple.com/reference/foundation/nsurlrequestcachepolicy/nsurlrequestreloadignoringlocalcachedata?language=objc

HTTP post w/ JSON to rails server from iOS

I have succeeded in making a post using a HTTP Client by setting the content type as application/json and this json code:
{
"order": {
"name": "Tia Carter",
"location": "Corams",
"phone_number": "707",
"food": "Bobcat Burger"
}
}
The code works perfect and the order is registered in the database. I am trying to work this into my iOS app but keep getting syntax errors regarding the colons in the json. This is the objective-c code:
NSURL *nsURL = [[NSURL alloc] initWithString:#"http://0.0.0.0:3000/orders.json"];
NSMutableURLRequest *nsMutableURLRequest = [[NSMutableURLRequest alloc] initWithURL:nsURL];
// Set the request's content type to application/x-www-form-urlencoded
[nsMutableURLRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// Set HTTP method to POST
[nsMutableURLRequest setHTTPMethod:#"POST"];
// Set up the parameters to send.
NSString *paramDataString = [NSString stringWithFormat:#
"{ "order": {"%#:" ="%#","%#:"="%#","%#:"="%#","%#:"="%#"}}", #"name", _name.text, #"location", _location.text, #"phone_number", _phoneNumber.text, #"food", _order.text];
// Encode the parameters to default for NSMutableURLRequest.
NSData *paramData = [paramDataString dataUsingEncoding:NSUTF8StringEncoding];
// Set the NSMutableURLRequest body data.
[nsMutableURLRequest setHTTPBody: paramData];
// Create NSURLConnection and start the request.
NSURLConnection *nsUrlConnection=[[NSURLConnection alloc]initWithRequest:nsMutableURLRequest delegate:self];
I'd appreciate any ideas or guidance. Thanks.
I believe you have two problems:
You didn't escape quotas (put \ before all of them)
You don't need to put text "name", "location" and etc in parameters (it's not a problem per se, just a style thing)
Also, I would recommend to work with NSDictionary and convert it to JSON when you need to (it will save you a lot of nerves for unescaped quotas, missing bracket and so on).
Look this question how to convert NSDictionary to JSON:
Generate JSON string from NSDictionary in iOS

Resources