Converting JSON to NSData, and NSData to JSON in Swift

Here is code to convert between JSON and NSData in swift 2.0 (adapted from Shuo’s answer) // Convert from NSData to json object func nsdataToJSON(data: NSData) -> AnyObject? { do { return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) } catch let myJSONError { print(myJSONError) } return nil } // Convert from JSON to nsdata func jsonToNSData(json: AnyObject) … Read more

NSMutableData remove bytes?

Please see the documentation of the following method: – (void)replaceBytesInRange:(NSRange)range withBytes:(const void *)replacementBytes length:(NSUInteger)replacementLength Apple says the following: If the length of range is not equal to replacementLength, the receiver is resized to accommodate the new bytes. Any bytes past range in the receiver are shifted to accommodate the new bytes. You can therefore pass … Read more

Convert unsigned char array to NSData and back

You can just use this NSData class method + (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length Something like NSUInteger size = // some size unsigned char array[size]; NSData* data = [NSData dataWithBytes:(const void *)array length:sizeof(unsigned char)*size]; You can then get the array back like this (if you know that it is the right data type) NSUInteger size = … Read more

Determine MIME type from NSData?

Based on ml’s answer from a similar post, I’ve added the mime types determination for NSData: ObjC: + (NSString *)mimeTypeForData:(NSData *)data { uint8_t c; [data getBytes:&c length:1]; switch (c) { case 0xFF: return @”image/jpeg”; break; case 0x89: return @”image/png”; break; case 0x47: return @”image/gif”; break; case 0x49: case 0x4D: return @”image/tiff”; break; case 0x25: return … Read more

NSData and Uploading Images via POST in iOS

This code works in my app. If you’re not using ARC you’ll need to modify the code to release anything alloc’ed. // create request NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setHTTPShouldHandleCookies:NO]; [request setTimeoutInterval:30]; [request setHTTPMethod:@”POST”]; // set Content-Type in HTTP header NSString *contentType = [NSString stringWithFormat:@”multipart/form-data; boundary=%@”, boundary]; [request setValue:contentType forHTTPHeaderField: @”Content-Type”]; … Read more

Create an Array in Swift from an NSData Object

You can use the getBytes method of NSData: // the number of elements: let count = data.length / sizeof(UInt32) // create array of appropriate length: var array = [UInt32](count: count, repeatedValue: 0) // copy bytes into array data.getBytes(&array, length:count * sizeof(UInt32)) print(array) // Output: [32, 4, 123, 4, 5, 2] Update for Swift 3 (Xcode … Read more