How to convert NSUUID to NSData - objective-c

I need to get NSData from vendorIdentifier without converting to NSString, clear bytes.
How to convert NSUUID using getUUIDBytes: to NSData?

NSUUID *vendorIdentifier = [[UIDevice currentDevice] identifierForVendor];
uuid_t uuid;
[vendorIdentifier getUUIDBytes:uuid];
NSData *vendorData = [NSData dataWithBytes:uuid length:16];

Use this to get the vendorIdentifier as Data (Swift 4):
var uuidBytes = UIDevice.current.identifierForVendor!.uuid
let uuidData = NSData(bytes: &uuidBytes, length: 16) as Data
Keep in mind to guard against UIDevice.current.identifierForVendor being nil as the documentation says.
Original answer (Swift 2 Version):
var uuidBytes: [UInt8] = [UInt8](count: 16, repeatedValue: 0)
UIDevice.currentDevice().identifierForVendor!.getUUIDBytes(&uuidBytes)
let uuidData = NSData(bytes: &uuidBytes, length: 16)

Swift 3 Version:
let vendorId = UIDevice.current.identifierForVendor!
let uuidBytes = Mirror(reflecting: vendorId.uuid).children.map { $0.1 as! UInt8 }
let data = Data(bytes: uuidBytes)

Related

Swift NSData Initialiser

I im tring to implement this method from a Obj-C library.
func bleDidReceiveData(data: UnsafeMutablePointer<UInt8>, length: Int32) {
var d = NSData(bytes: data as [UInt8], length: length)
}
However when i tried initializing NSData, it gave me this error
Cannot find an initialiser for type NSData that accepts an argument of type (bytes:[UInt8],length:int32)
In Obj-C it is being done this way
NSData *d = [NSData dataWithBytes:data length:length];
func bleDidReceiveData(data: UnsafeMutablePointer<UInt8>, length: Int32) {
var d = NSData(bytes: UnsafeMutablePointer<Void>(data), length: Int(length))
}

Convert AVPlayer NSData to NSString (Or player format)

I need to know how to convert saved NSData from an AVPlayer back into a playable format. But I cannot figure out how to convert this NSData into a dataString, which would then allow me to create and NSUrl. Let's say I have the following code:
NSURL *videoUrl=(NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];
self.data=[NSData dataWithContentsOfURL:videoUrl];
Now later on when I get this data back, I call:
NSString *dataString = [NSString stringWithUTF8String:[self.data bytes]];
But the dataString is always nil. Why? Am I decoding it in the wrong format or something?
A URL is a reference to data. The data is a (possibly complicated) encoding of something like a movie.
I am not sure exactly what you are asking, but I think you want to get the data (as an NSData object) and then save it somewhere. If this is correct, then what you need to do is
[self.data writeToFile:myFilePath atomically:YES]
where myFilePath is a path to somewhere where you can store files.
You could implement AVAssetResourceLoaderDelegate to provide data for AVPlayer.
func resourceLoader(resourceLoader: AVAssetResourceLoader!, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest!) -> Bool {
if let data = videoData {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
if let infoRequest = loadingRequest.contentInformationRequest {
infoRequest.contentType = "public.mpeg-4" // UTI
infoRequest.contentLength = Int64(data.length)
infoRequest.byteRangeAccessSupported = true
}
if let request = loadingRequest.dataRequest {
let part = data.subdataWithRange(NSRange(location: Int(request.requestedOffset), length: Int(request.requestedLength)))
request.respondWithData(part)
}
loadingRequest.finishLoading()
}
return true
}
return false
}
To create an AVPlayer:
let asset = AVURLAsset(URL: NSURL(scheme: "yourcustomscheme", host: nil, path: "/pathtovideo"), options: nil)
asset.resourceLoader.setDelegate(self, queue: dispatch_get_main_queue())
let item = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: item)

NSString to NSData using stringWithUTF8String and dataUsingEncoding returns nil

When i convert the NSString to NSData and back i get a nil result
NSString * test = #"Wft0r3qkzXd5TDBeCahUB3MtHuc8Axwr";
NSData * testData = [test dataUsingEncoding:NSUTF8StringEncoding];
NSString * result = [NSString stringWithUTF8String:[testData bytes]];
Out
Printing description of testData:
<57667430 7233716b 7a586435 54444265 43616855 42334d74 48756338 41787772>
Printing description of result:
<nil>
I believe you're looking for this method:
- (instancetype)initWithData:(NSData *)data
encoding:(NSStringEncoding)encoding
From the apple doc's here: NSString class reference
In Swift, you can see the round-trip from string to data to string as follows:
let srcString = "Wft0r3qkzXd5TDBeCahUB3MtHuc8Axwr"
let stringAsData = srcString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let dstString = NSString(data: stringAsData, encoding: NSUTF8StringEncoding)!
dstString // => "Wft0r3qkzXd5TDBeCahUB3MtHuc8Axwr"
Basically, you want to use NSString(data:NSData,encoding:UInt) not NSString(UTF8String:UnsafePointer<Int8>).
An NSData is a Cocoa object that wraps a buffer of bytes. But the method you were using takes an UnsafePointer<Int8>, in other words, a raw pointer, which is just a numerical memory address pointing to the start of an array of bytes.
Swift 3
let string = "aHft0r3qkzjuh5rdsaeCahUB3MtHuc8Axwrfdvxgf"
let stringData = string.data(using: String.Encoding.utf8, allowLossyConversion: false)!
let finalString = NSString(data: stringData, encoding: String.Encoding.utf8.rawValue)!;

obj-c to Swift convert code

So I'm trying to convert some obj-c code into swift but I'm stuck on a part of it.
How can I do something like this in swift?
- (void)sometMethod:(NSString *)s {
NSString * crlfString = [s stringByAppendingString:#"\r\n"];
uint8_t *buf = (uint8_t *)[crlfString UTF8String];}
The real problem is this line
uint8_t *buf = (uint8_t *)[crlfString UTF8String];
What do you want to do with the UTF-8 buffer? Generally, it is more convenient to convert the string directly to an NSData object. But you can also translate your Obj-C code one by one to Swift. Here are both variants:
import Foundation
func appendCRLFAndConvertToUTF8_1(s: String) -> NSData {
let crlfString: NSString = s.stringByAppendingString("\r\n")
let buffer = crlfString.UTF8String
let bufferLength = crlfString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
let data = NSData(bytes: buffer, length: bufferLength)
return data;
}
func appendCRLFAndConvertToUTF8_2(s: String) -> NSData {
let crlfString = s + "\r\n"
return crlfString.dataUsingEncoding(NSUTF8StringEncoding)!
}
let s = "Hello 😄"
let data1 = appendCRLFAndConvertToUTF8_1(s)
data1.description
let data2 = appendCRLFAndConvertToUTF8_2(s)
data2.description
data1 == data2
And if you want to iterate over the UTF-8 code units and not deal with a buffer, use something like:
for codeUnit in String.utf8 {
println(codeUnit)
}

How to show Emoji in UILabel iOS

I have to show the textview text smily in UILabel.
In the UILabel -
lbl.text = #"Happy to help you \U0001F431;
its showing properly.
In UITextView -
I tried to convert UITextView text in string and then log is -
%F0%9F%99%88%F0%9F%99%89%F0%9F%99%8A
How to encode which i can show in UILabel, anybody please suggest me.
You can use ⌃ ⌘ Space shortcut to show the symbols panels and just insert the emoji you're looking for directly without unicode:
lbl.text = #"Happy to help you 😺";
(just copy the code above to Xcode if you browser doesn't show the emoji)
NSString *str = #"Happy to help you \U0001F431";
NSData *data = [str dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *valueUnicode = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *dataa = [valueUnicode dataUsingEncoding:NSUTF8StringEncoding];
NSString *valueEmoj = [[NSString alloc] initWithData:dataa encoding:NSNonLossyASCIIStringEncoding];
_lbl.text = valueEmoj;
SWIFT - 3 OR HIGHER
let str = "Happy to help you \U0001F431"
let data : NSData = str.dataUsingEncoding(NSNonLossyASCIIStringEncoding)!
let valueUnicode : String = String(data: data, encoding: NSUTF8StringEncoding)!
let dataa : NSData = valueUniCode.dataUsingEncoding(NSUTF8StringEncoding)!
let valueEmoj : String = String(data: dataa, encoding: NSNonLossyASCIIStringEncoding)!
SWIFT - 4 OR HIGHER
let str = "Happy to help you \U0001F431"
let data : NSData = str.dataUsingEncoding(NSNonLossyASCIIStringEncoding)!
let valueUnicode : String = String(data: data as Data, encoding: String.Encoding.utf8)!
let dataa : NSData = valueUnicode.data(using: String.Encoding.utf8)! as NSData
let valueEmoj : String = String(data: dataa as Data, encoding: String.Encoding.nonLossyASCII)!
On Xcode version 7.2.1,
You can use the below shortcut to show the symbols panels and insert the emoji:
shortcut:
(pressed the below three keys together)
Ctrl Command Space
Swift 3.0 solution update given by #Bhavesh Nayi
let data = txtMessage.text!.data(using: .nonLossyASCII)
let emojiString = String.init(data: data!, encoding: .utf8)
and Send it to Chat Server as a
let data = message.message.data(using: .utf8)
let emoji = String.init(data: data!, encoding: .nonLossyASCII)
and Then Show emoji to UILablel
In case of swift 2.3 or lower
let textViewData : NSData = textViewString.dataUsingEncoding(NSNonLossyASCIIStringEncoding)!
let valueUniCode : String = String(data: textViewData, encoding: NSUTF8StringEncoding)!
let emojData : NSData = valueUniCode.dataUsingEncoding(NSUTF8StringEncoding)!
let emojString : String = String(data: emojData, encoding: NSNonLossyASCIIStringEncoding)!
In Case of Swift 3.0 or higher
let textViewData = textViewString.data(using: .nonLossyASCII)
let valueUniCode = String.init(data: textViewData!, encoding: .utf8)!
let emojData = valueUniCode.data(using: .utf8)
let emojString = String.init(data: emojData, encoding: .nonLossyASCII)