I have an example in Swift language:
guard let windowScene = view.window?.windowScene else { return }
windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: .portrait)) { error in }
I can't write it in Objective C:
UIWindowScene *windowScene = self.view.window.windowScene;
[windowScene requestGeometryUpdateWithPreferences: UIInterfaceOrientationMaskPortrait errorHandler:nil];
Please tell me how to write correctly I will be grateful for any help.
One way to write that Swift code in Objective-C would be:
UIWindowScene *windowScene = self.view.window.windowScene;
if (!windowScene) { return; }
UIWindowSceneGeometryPreferences *preferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskPortrait];
[windowScene requestGeometryUpdateWithPreferences:preferences errorHandler:^(NSError * _Nonnull error) {
// Handle error here
}];
Related
Trying to implement "Swipe to Delete" API for UICollectionViewListCell.
I'm writing in Objective-C
the compiler is not auto-completing the code.
Any reasons? example code?
Swift example:
let listConfig = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
listConfig.trailingSwipeActionsConfigurationProvider = { [weak self] indexPath in
guard let self = self else { return nil }
let action = UIContextualAction(style: .normal, title: "Done!", handler: actionHandler)
return UISwipeActionsConfiguration(actions: [action])
}
Any code example for Objective C?
trying to reach the following result:
UICollectionLayoutListConfiguration * listConfiguration = [[UICollectionLayoutListConfiguration alloc]initWithAppearance:UICollectionLayoutListAppearanceInsetGrouped];
[listConfiguration setTrailingSwipeActionsConfigurationProvider:^UISwipeActionsConfiguration* (NSIndexPath *indexPath) {
UIContextualAction *action = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:[NSLocalizedString(#"Delete", nil)capitalizedString] handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
}];
return [UISwipeActionsConfiguration configurationWithActions:#[action]];
}];
I'm trying to convert this text to swift:
- (void)sendData:(NSData*)data
{
NSError *error;
GameKitHelper *gameKitHelper = [GameKitHelper sharedGameKitHelper];
BOOL success = [gameKitHelper.match
sendDataToAllPlayers:data
withDataMode:GKMatchSendDataReliable
error:&error];
if (!success) {
NSLog(#"Error sending data:%#", error.localizedDescription);
[self matchEnded];
}
}
Now I've gotten so far here:
func sendData(data: NSData) {
var error: NSError?
var gameKitHelper = GameKitHelper.sharedGameKitHelper()
var success = try! gameKitHelper.match.sendDataToAllPlayers(data, withDataMode: GKMatchSendDataReliable)
if !success {
print("Error sending data:\(error.localizedDescription)")
self.matchEnded()
}
}
But It's giving me an error at if (!succes) and I read on apples documentation that the objective-c version of .sendDataToAllPlayers() will return a bool but the swift version won't.
Apple Documentation - GKMatch
So how can I handle the error
The sendDataToAllPlayers function throws an exception if an error occurs. You need a catch block to handle it:
func sendData(data: NSData) {
var gameKitHelper = GameKitHelper.sharedGameKitHelper()
do {
try gameKitHelper.match.sendDataToAllPlayers(data, withDataMode: .Reliable)
}
catch let error as NSError {
print("Error sending data:\(error.localizedDescription)")
self.matchEnded()
}
}
I do not know how to convert the following Objective-C code into swift. How should I do ?
Objective-c
if (operations) {
if ([operations isKindOfClass:[NSArray class]]) {
for (id <MyOperation> operation in operations) {
if (operation) {
[operation cancel];
}
}
} else if ([operations conformsToProtocol:#protocol(MyOperation)]){
[(id<MyOperation>) operations cancel];
}
[operationDictionary removeObjectForKey:key];
}
swift
if operations != nil {
// doto .......
}
Try this code:
if operations != nil {
// doto .......
if (operations?.isKindOfClass(NSArray) != nil){
for operation in operations as! [MyOperation]{
operation.cancle()
}
} else if operations?.conformsToProtocol(MyOperation){
(operations as MyOperation).cancle()
}
operationDictionary.removeObjectForKey(key)
}
I didn't test it so may be you have to make little bit changes into this code.
Hope this will help.
I usually don't help people with complete conversions, but...
if let operations: AnyObject = operations {
if operations is NSArray {
for operation in operations as! [MyOperation] {
operation.cancel()
}
}
else if let operation = operations as? MyOperation {
operation.cancel()
}
operationDictionary.removeObjectForKey(key)
}
I searched on google and on SO but didn't find any useful help for this issue.
I'm trying to translate this code from objective-c to swift:
- (void)metaTitleUpdated:(NSString *)title {
NSLog(#"delegate title updated to %#", title);
NSArray *chunks = [title componentsSeparatedByString:#";"];
if ([chunks count]) {
NSArray *streamTitle = [[chunks objectAtIndex:0] componentsSeparatedByString:#"="];
if ([streamTitle count] > 1) {
titleLabel.text = [streamTitle objectAtIndex:1];
}
}
}
so far i have translated it to this:
func metaTitleUpdated(input: String) {
println("delegate title updated to \(title)")
let chunks: NSArray = title!.componentsSeparatedByString(";")
if (chunks.count) {
let streamTitle = chunks .objectAtIndex(0) .componentsSeparatedByString(";")
if (streamTitle.count > 1) {
titleLabel.text = streamTitle.objectAtIndex(1)
}
}
}
but i always get the error "Type 'Int' does not conform to protocol 'BooleanType'" in the line: if (chunks.count) {
What does cause this error? Is the rest of the code in swift correct or are there any other errors?
chunks.count has the type Int, but the if statement requires a boolean expression.
This is different from (Objective-)C, where the controlling expression of an if statement can have any scalar type and is compared with zero.
So the corresponding Swift code for
if ([chunks count]) { ... }
is
if chunks.count != 0 { ... }
I solved the answer by myself.
func metaTitleUpdated(title: String) {
var StreamTitle = split(title) {$0 == "="}
var derRichtigeTitel: String = StreamTitle[1]
titleLabel.text = derRichtigeTitel
println("delegate title updated to \(derRichtigeTitel)")
}
I'm building an app that allows users to drop videos onto it. Given a list of dropped NSURL*s how do I make sure each one conforms to the public.movie UTI type?
If I had an NSOpenPanel, I would just use openPanel.allowedFileTypes = #[#"public.movie"]; and Cocoa would take care of it for me.
Thanks in advance!
This should work:
NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
for (NSURL *url in urls) {
NSString *type;
NSError *error;
if ([url getResourceValue:&type forKey:NSURLTypeIdentifierKey error:&error]) {
if ([workspace type:type conformsToType:#"public.movie"]) {
// the URL points to a movie; do stuff here
}
} else {
// handle error
}
}
(You can also use UTTypeConformsTo() instead of the NSWorkspace method.)
Swift version:
do {
var value: AnyObject?
try url.getResourceValue(&value, forKey:NSURLTypeIdentifierKey)
if let type = value as? String {
if UTTypeConformsTo(type, kUTTypeMovie) {
...
}
}
}
catch {
}
Swift 5 version:
if let resourceValues = try? localUrl.resourceValues(forKeys: [URLResourceKey.typeIdentifierKey]) {
if let typeId = resourceValues.typeIdentifier {
if UTTypeConformsTo(type, kUTTypeMovie) {
...
}
}
}