I am trying to go on with a project but maybe i am asking the wrong questions to google.
I have been using NSURLConnection to download files
NSURLRequest * XMLRequested = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://kilkadg.com/cursos/images/imagenes.xml"]];
NSURLConnection * conexion = [[NSURLConnection alloc] initWithRequest:XMLRequested delegate:self];
and implement the next methods
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[imagenBytes appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[imagenBytes writeToFile:[DataImage imagenSource:self.name] atomically:YES];
}
Now I want to do it in the other way. I want a file created in the iPad, as a photo or a sound, save it in my server.
I havenĀ“t find which class to use, neither how to receive that data in my server.
Thanks
For the creation of sound in the iPad I used http://www.techotopia.com/index.php/Recording_Audio_on_an_iPhone_with_AVAudioRecorder_%28iOS_4%29
To send Post data and files I used this link http://zcentric.com/2008/08/29/post-a-uiimage-to-the-web/#comment-8145
So instead of save a .png I saved a .caf
Related
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.
I'm trying to modify a behavior of a webpage within my iOS app and make the in-page media player play a file from the local caches folder instead of fetching it from a web server.
Below is my code that replaces the http:// video path with a local file path. The code does not work, giving me "Resource Temporary not available. Please try again" error message popup. Is it possible to have a web-based media player play file from a local disk using file URL?
I tried substituting these for the instanceURL, but they don't seem to work.
[fileURL path]
[fileURL absolutePath]
I'm intercepting the request for the file and am parsing it to find out that the page is asking for a video file:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
// An NSURLConnection delegate callback. We pass this on to the client.
{
NSDictionary* decisionDictionary = [[RequestListener sharedInstance] shouldContinue:connection processRequestData:data];
BOOL shouldContinue = [decisionDictionary[#"shouldContinue"] boolValue];
if(shouldContinue == NO)
{
return;
}else
{
NSData* d = data;
//substitute fake data
if(decisionDictionary[#"data"])
{
d = decisionDictionary[#"data"];
}
[[self client] URLProtocol:self didLoadData:d];
}
}
Within my shouldContinue method, I check if the video is present locally and modify the response data to create a path to a local video.
NSString* path = [VideoDownloader localVideoPathForVideoID:videoID];
NSURL* fileURL = [NSURL fileURLWithPath:path];
DLog(#"url:%#",[fileURL absoluteString]);
NSString* replacement = [NSString stringWithFormat:#"\"instanceUrl\":\"%#\"",[[fileURL absoluteURL] absoluteString]];
DLog(#"replacement:%#",replacement);
NSString* forgedResponse = [parts componentsJoinedByString:#","];
NSData* forgedData = [forgedResponse dataUsingEncoding:NSUTF8StringEncoding];
return #{#"shouldContinue":#(YES),#"data":forgedData};
Have a look at NSURLProtocol. You can intercept http requests before they are sent to a host to decide what to do about it: Continue to server, redirect to local cache.
There's a decent tutorial by our beloved Ray Wenderlich.
Apple has a programming guide as well.
I have data on a server and I am trying getting this data as a piped string. I wrote the sever-side code but I don't know how can I retrieve this data and parse it in iOS. Here is an example of my data. Is there any article or code that can help me?
A few starting points: For retrieving a stream of data from a server, have a look at Apple's Stream Programming Guide. To parse your data, you can use a NSScanner (String Programming Guide: Scanners) or a CFXMLParser (XML Programming Topics for Core Foundation) if you have valid XML data.
Your output doesn't seem to be in a valid format like xml or json. But if your glat with the content as a string inside your app use this code snippet
- (void)viewDidLoad{
[super viewDidLoad];
NSURLRequest *site_request =
[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://...."]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLConnection *site_connection =
[[NSURLConnection alloc] initWithRequest:site_request
delegate:self];
}
- (void)connection:(NSURLConnection *)site_connection didReceiveData:(NSData *)data{
NSString *site_response =
[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"OUTPUT: %#", site_response);
}
The log will put out the string inside the console.
I have a NSURLConnection that receives data output from a url pointing to a php script on my server.
Most of the time everything works fine and the data is retrieved in its complete form.
However, sometimes I receive NULL or broken (i.e. the bottom half) of data at:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
When this happens, if I reload the connection it will always return the same null or broken block
of data for the request.
EDIT*:
I've realized that when I receive what I thought was nil data, I actually received data
but the NSString created from this data is nil. I still don't understand why though. My php encoding output is always UTF-8 so I don't think it is an issue of encoding and besides it works most of the time with this.
I have checked the php script with that same request to verify that it is not a problem on the server side or with the php script and confirmed that it is NOT.
My code is Below:
-(void)setUpConnectionAndMakeRequest {
NSString *URLpath = #"http://www.example.com/myphp.php";
NSURL *myURL = [[NSURL alloc] initWithString:URLpath];
NSMutableURLRequest *myURLRequest = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[myURL release];
[myURLRequest setHTTPMethod:#"POST"];
//I added this because I thought it may be a problem relating to cache but it isn't
NSURLCache *cache = [NSURLCache sharedURLCache];
[cache removeAllCachedResponses];
NSString *httpBodystr = [NSString stringWithString:#"command=runscript"];
[myURLRequest setHTTPBody:[httpBodystr dataUsingEncoding:NSUTF8StringEncoding]];
[mailData setData:nil]; //mailData is a NSMutableData object which accumulates the data retrieved by the request
[NSURLConnection connectionWithRequest:myURLRequest delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *untrimmedDataSTR = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; //Created so I can see the data (always text) in NSLog
NSLog(#"Live Data: %#", untrimmedDataSTR); //This is where I see that the data is broken or null when it shouldn't be
[mailData appendData:data]; //Append accumulated data to NSMutableData object used later in my app.
[untrimmedDataSTR release];
}
Any help would be much appreciated.
According to the NSString reference, -initWithData:encoding: returns nil if "the initialization fails for some reason (for example if data does not represent valid data for encoding)."
That almost certainly means that the response from the server is not, in fact, UTF-8 encoded data.
The way to check would be to NSLog the data before trying to convert to an NSString:
NSLog(#"Raw Data: %#", data);
(The -description method on NSData will return a hexadecimal representation of the contents; that's what will get logged).
Is it possible to use the:
[NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething];
In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file?
for example:
I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array.
NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:#"One",#"Two",nil];
[arrayToWrite writeToURL:
[NSURL urlWithString:#"mywebsite.atwebpages.com/myArray.plist"] atomically:YES];
And at runtime:
NSMutableArray *arrayToRead =
[[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:#"mywebsite.atwebpages.com/myArray.plist"]];
Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net, the URL receives the information and updates server sided files accordingly.
A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
As for part one of your question,
I'll assume you want to use the contents of a NSMutableArray to form some sort of a URL request (like POST) that you will send to your web service and expect back some information...
There is no prebuilt way of sending the contents of a NSMutableArray to an URL but there are simple ways of doing this yourself. For example, you can loop through the data of your array and make use of NSURLRequest to create a URL request that complies with the interface of your web service. Once you've constructed your request you can send it by passing it a NSURLConnection object.
Consider this very simple and incomplete example of what the client-side code might look like using an Obj-C array to provide data...
NSMutableData *dataReceived; // Assume exists and is initialized
NSURLConnection *myConnection;
- (void)startRequest{
NSLog(#"Start");
NSString *baseURLAddress = #"http://en.wikipedia.org/wiki/";
// This is the array we'll use to help make the URL request
NSArray *names = [NSArray arrayWithObjects: #"Jonny_Appleseed",nil];
NSString *completeURLAsString = [baseURLAddress stringByAppendingString: [names objectAtIndex:0]];
//NSURLRequest needs a NSURL Object
NSURL *completeURL = [NSURL URLWithString: completeURLAsString];
NSURLRequest *myURLRequest = [NSURLRequest requestWithURL: completeURL];
// self is the delegate, this means that this object will hanlde
// call-backs as the data transmission from the web server progresses
myConnection = [[NSURLConnection alloc] initWithRequest:myURLRequest delegate: self startImmediately:YES];
}
// This is called automatically when there is new data from the web server,
// we collect the server response and save it
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"Got some");
[dataReceived appendData: data];
}
// This is called automatically when transmission of data is complete
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// You now have whatever the server sent...
}
To tackle part 2 of your question, the receiver of a web request will likely require some scripting or infrastructure to make a useful response.
Here, Answer in this question:
Creating a highscore like system, iPhone side
I couldn't edit my post because I posted from my iPhone as an anonymous user, sorry.