I want to convert local resource folder video file(12345.mp4) to base64 encoding string and then send into the server side from API but web team telling invalid base64 encoded string. Is this correct?
This is my code :
NSString *base64String = #"";
NSError *error;
NSData *videoData;
NSString *strVideoPath = [[NSBundle mainBundle] pathForResource:#"12345" ofType:#"mp4"];
videoData = [[NSData alloc]initWithContentsOfFile:strVideoPath options:NSDataReadingMappedIfSafe error:&error];
base64String = [videoData base64EncodedStringWithOptions:0];
In swift version you can convert video like this
*let tempURL = info[UIImagePickerController.InfoKey.mediaURL]
let data = NSData(contentsOf: tempURL as! URL)
print("\(String(describing: data?.length))")
if data?.length ?? 0 > 0{
guard data != nil else {
return
}
let base64String = data!.base64EncodedString(options: .lineLength64Characters)
self.video = base64String
}*
Related
I need to extract some data from a http header. Prior to being sent by the server, the data has been base64 encoded and then URL encoded. The header looks like:
<snip>
Server = Apache;
"Transfer-Encoding" = Identity;
"Www-Authenticate" = "Basic realm=\"itYNcEpMfSPfewXAOte3II6xXsM6aNBO197bBuvb9gvWVl7Xo%2FQJ9j9r0hHz0k12xLRqlyvczoCM7kI9q1opHj%2BKYiPz73DqypNFgYGleR3n0bcVTto80Hq55i6nsgPaCnHrWJOdQs1HY%2FzzuK6vbZYAIofiB7VKSwdi00ZmkbQi9Pi05i4lCaCu%2FwV%2FXOOS95oL8TQ%3D\"";
In order to remove the URL encoding and base64 encoding, should I extract the raw header data as an NSString or as NSData?
NSString* option1 = [header objectForKey: #"Www-Authenticate"];
NSData* option2 = [header objectForKey: #"Www-Authenticate"];
Is it important to choose one over the other, or could both options be used equally?
(Note I'm not asking how to decode from URL encoding and decode from Base64, I'm asking if the starting point should be as NSString or NSData and why, or it doesn't matter).
base64 this is string, which you can convert to NSData.
NSString* option1 = [header objectForKey: #"Www-Authenticate"];
NSData *data = [NSData dataFromBase64String:option1];
- (NSString*)encodeTo64:(NSString*)fromString
{
NSData *plainData = [fromString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String;
if ([plainData respondsToSelector:#selector(base64EncodedStringWithOptions:)]) {
base64String = [plainData base64EncodedStringWithOptions:kNilOptions]; // iOS 7+
} else {
base64String = [plainData base64Encoding]; // pre iOS7
}
return base64String;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How to get image from directory then convert it into base64string and send it through web service.
You can do this:
// Gets image from your file directory
UIImage *image = [UIImage imageWithContentsOfFile:#"path/to/your/directory"];
// Converts it to NSData type.
NSData *imageData = UIImageJPEGRepresentation(image, 1);
// Converts it to base64 string.
NSString *encodedString = [imageData base64Encoding];
// Swift
var image: UIImage = UIImage.imageWithContentsOfFile("path/to/your/directory")!
// Converts it to NSData type.
var imageData: NSData = UIImageJPEGRepresentation(image, 1)
// Converts it to base64 string.
var encodedString: String = imageData.base64Encoding()
I have added all three scenarios (The three examples are not related at all)
1. Converting the image.
2. Finding the image from the files directory
3. Posting the image on the server
Here is how you create a base64 image
//Use image name from bundle to create NSData
let image : UIImage = UIImage(named:"imageNameHere")!
//Now use image to create into NSData format
let imageData:NSData = UIImagePNGRepresentation(image)!
//OR next possibility
//Use image's path to create NSData
let url:NSURL = NSURL(string : "urlHere")!
//Now use image to create into NSData format
let imageData:NSData = NSData.init(contentsOfURL: url)!
Here is how you find the image from the file manager
NSString *searchFilename = #"hello.png"; // name of the PDF you are searching for
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
NSString *documentsSubpath;
while (documentsSubpath = [direnum nextObject])
{
if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
continue;
}
NSLog(#"found %#", documentsSubpath);
}
To send the request, I used NSMutableURLRequest to handle the JSON request
var request = NSMutableURLRequest(URL: NSURL(string: url))
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
To prepare the HTTPBody, I had to encode the image to a Base64 string. This is done through the following:
var imageData = UIImageJPEGRepresentation(image, 0.9)
var base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!) // encode the image
After doing this, I’ve put the encoded image into a Dictionary in the appropriate parameter. I serialized it into a JSON representation which I assigned to the HTTPBody.
var err: NSError? = nil
var params = ["image":[ "content_type": "image/jpeg", "filename":"test.jpg", "file_data": base64String]]
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions(0), error: &err)!
I used the shared session object to create a task to send the request. I created a request model that I can convert to a MutableURLRequest. You can see how it looks like here.
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request.toMutableURLRequest(), completionHandler: { data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
var err: NSError?
// process the response
})
task.resume() // this is needed to start the task
After the request has completed, the block I passed via the completionHandler will be executed. From there, I was able to evaluate the response. So that’s how I was able to send the image taken from my phone’s camera to the server.
I have a video I'm fetching from my server and receiving as data. I'm trying to cover the raw data into a URL so that I can use it to instantiate an AVPlayerItem and play the video on the phone. However, this code returns nil when I print "videoDataString". If I print "videoData" there is a result though. Here is my code where I try to convert, is my mistake the encoding part?
let videoDataString = NSString(data: videoData, encoding: NSUTF8StringEncoding)
let videoURL = NSURL(string: String(videoDataString))
First Save your Video data to a file then try to access that as a file URL.
Here is an example.
NSString *filePath = [self documentsPathForFileName:#"video.mp4"];
NSData *videoAsData; // your data here
[videoAsData writeToFile:filePath atomically:YES];
// access video as URL
NSURL *videoFileURL = [NSURL fileURLWithPath:filePath];
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return [documentsPath stringByAppendingPathComponent:name];
}
For Swift 3.0:
let filePath = self.documentsPathForFileName("video.mp4")
let videoAsData = NSData()
videoAsData.write(toFile: filePath, atomically: true)
let videoFileURL = NSURL(fileURLWithPath: filePath)
func documentsPathForFileName(name: String) -> String {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
return documentsPath.appending(name)
}
You cannot convert all strings to URL. URL is Uniform Resource Locator. That means it is a string containing the path to the file or resource in remote or local destination. If you want to keep your video data and instantiate video player with that video, first save the video data to a file, then instantiate video player with path to that file.
Use following code for this
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let videoURL = documentsURL.URLByAppendingPathComponent("video.mp4")//what ever your filename and extention
videoData.writeToURL(videoURL, atomically: true)
//uese videoURL to instantiate video player
does anyone know how to get a list of custom fonts from the 'Fonts provided by application' key in the info.plist file in Xcode?
Thanks
The following code reads the list of custom font files from the Info.plist,
and extracts the full font name from the font file.
(Parts of the code is copied from https://stackoverflow.com/a/17519740/1187415
with small modifications and ARC adjustments).
Objective-C
NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
NSArray* fontFiles = [infoDict objectForKey:#"UIAppFonts"];
for (NSString *fontFile in fontFiles) {
NSLog(#"file name: %#", fontFile);
NSURL *url = [[NSBundle mainBundle] URLForResource:fontFile withExtension:NULL];
NSData *fontData = [NSData dataWithContentsOfURL:url];
CGDataProviderRef fontDataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)fontData);
CGFontRef loadedFont = CGFontCreateWithDataProvider(fontDataProvider);
NSString *fullName = CFBridgingRelease(CGFontCopyFullName(loadedFont));
CGFontRelease(loadedFont);
CGDataProviderRelease(fontDataProvider);
NSLog(#"font name: %#", fullName);
}
Swift 3 equivalent:
if let infoDict = Bundle.main.infoDictionary,
let fontFiles = infoDict["UIAppFonts"] as? [String] {
for fontFile in fontFiles {
print("file name", fontFile)
if let url = Bundle.main.url(forResource: fontFile, withExtension: nil),
let fontData = NSData(contentsOf: url),
let fontDataProvider = CGDataProvider(data: fontData) {
let loadedFont = CGFont(fontDataProvider)
if let fullName = loadedFont.fullName {
print("font name", fullName)
}
}
}
}
You can add your costume font http://www.danielhanly.com/blog/tutorial/including-custom-fonts-in-ios/
But, I don't, know how to get this list, sorry.
But, may be you can look on it in IB, in UILabel attributes.
How do I convert an NSString value to NSData?
NSString* str = #"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSString *str = #"helowrld";
// This converts the string to an NSData object
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
you can take reference from this link
Do:
NSData *data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
then feel free to proceed with NSJSONSerialization:JSONObjectWithData.
Correction to the answer regarding the NULL terminator
Following the comments, official documentation, and verifications, this answer was updated regarding the removal of an alleged NULL terminator:
As documented by dataUsingEncoding::
Return Value
The result of invoking dataUsingEncoding:allowLossyConversion: with NO as the second argument
As documented by getCString:maxLength:encoding: and cStringUsingEncoding::
note that the data returned by dataUsingEncoding:allowLossyConversion: is not a strict C-string since it does not have a NULL terminator
In case of Swift Developer coming here,
to convert from NSString / String to NSData
var _nsdata = _nsstring.dataUsingEncoding(NSUTF8StringEncoding)
Objective-C:
NSString *str = #"test string";
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:str];
NSString *thatStr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Swift:
let str = "test string"
let data = NSKeyedArchiver.archivedData(withRootObject: str)
let thatStr = NSKeyedUnarchiver.unarchiveObject(with: data) as! String
First off, you should use dataUsingEncoding: instead of going through UTF8String. You only use UTF8String when you need a C string in that encoding.
Then, for UTF-16, just pass NSUnicodeStringEncoding instead of NSUTF8StringEncoding in your dataUsingEncoding: message.
For Swift 3, you will mostly be converting from String to Data.
let myString = "test"
let myData = myString.data(using: .utf8)
print(myData) // Optional(Data)
NSString *str = #"hello";
NSData *data = [NSData dataWithBytes:str.UTF8String length:str.length];
Objective-C:
NSString to NSData:
NSString* str= #"string";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSData to NSString:
NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
Swift:
String to Data:
var testString = "string"
var somedata = testString.data(using: String.Encoding.utf8)
Data to String:
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!
Update Swift 5.x
let str = "teststring"
let data = str.data(using: .utf8)
Swift:
Swift 5.x
let myStringToConvert = "My String to Convert in Data"
let myData = myStringToConvert.data(using: .utf8)
String to Data:
var myStringToConvert = "My String to Convert in Data"
var myData = myStringToConvert.data(using: String.Encoding.utf8)
Data to String:
var backToMyString = String(data: myData!, encoding: String.Encoding.utf8) as String!
OBJECTIVE C:
NSString to NSData :
NSString* myStringToConvert= #"My String to Convert in Data";
NSData* myData=[str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSData to NSString :
NSString* backToMyString = [[NSString alloc] initWithData: myData encoding:NSUTF8StringEncoding];
NSString *str = #"Banana";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:true];
Objective-C
NSString *str = #"Hello World";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
Swift
let str = "Hello World"
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
In Swift there is an API which returns a non-optional
let str = "teststring"
let data = Data(str.utf8)