如何将NSUrl转换为NSString?

时间:2022-02-21 00:14:51

After AVAssetExportSession has complete export video. I have plan to garb Video Path to upload via Youtube. but [GDataUtilities MIMETypeForFileAtPath:path defaultMIMEType:@"video/mp4"]; it only accept NSString. Is it possible to convert NSUrl in to NSString for video file path.

AVAssetExportSession完成导出视频后。我计划通过Youtube上传视频路径。但是[GDataUtilities MIMETypeForFileAtPath:path defaultMIMEType:@“video / mp4”];它只接受NSString。是否可以将NSUrl转换为NSString用于视频文件路径。

i have try to use NSString *path = [ExportoutputURL absoluteString]; but it crash.

我试着使用NSString * path = [ExportoutputURL absoluteString];但它崩溃了。

Here is the Code

这是守则

- (void)exportDidFinish:(AVAssetExportSession*)session {
    ExportoutputURL = session.outputURL;

    _exporting = NO;
    NSIndexPath *exportCellIndexPath = [NSIndexPath indexPathForRow:2 inSection:kProjectSection];
    ExportCell *cell = (ExportCell*)[self.tableView cellForRowAtIndexPath:exportCellIndexPath];
    cell.progressView.progress = 1.0;
    [cell setProgressViewHidden:YES animated:YES];
    [self updateCell:cell forRowAtIndexPath:exportCellIndexPath];

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:ExportoutputURL]) {
        [library writeVideoAtPathToSavedPhotosAlbum:ExportoutputURL
                                    completionBlock:^(NSURL *assetURL, NSError *error){
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            if (error) {
                                                NSLog(@"writeVideoToAssestsLibrary failed: %@", error);
                                                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[error localizedDescription]
                                                                                                    message:[error localizedRecoverySuggestion]
                                                                                                   delegate:nil
                                                                                          cancelButtonTitle:@"OK"
                                                                                          otherButtonTitles:nil];
                                                [alertView show];
                                                [alertView release];
                                            }
                                            else {
                                                _showSavedVideoToAssestsLibrary = YES;
                                                ExportCell *cell = (ExportCell*)[self.tableView cellForRowAtIndexPath:exportCellIndexPath];
                                                [cell setDetailTextLabelHidden:NO animated:YES];
                                                [self updateCell:cell forRowAtIndexPath:exportCellIndexPath];
                                                NSArray *modes = [[[NSArray alloc] initWithObjects:NSDefaultRunLoopMode, UITrackingRunLoopMode, nil] autorelease];
                                                [self performSelector:@selector(hideCameraRollText) withObject:nil afterDelay:5.0 inModes:modes];
                                            }
                                        });

                                    }];
    }
    [library release];
}

- (void)uploadVideoFile {

    NSString *devKey = DEVELOPER_KEY;

    GDataServiceGoogleYouTube *service = [self youTubeService];
    [service setYouTubeDeveloperKey:devKey];

    NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:kGDataServiceDefaultUser];

    // load the file data
    NSString *path = [ExportoutputURL absoluteString];//[[NSBundle mainBundle] pathForResource:@"video_2451" ofType:@"mp4"];//[mFilePathField stringValue];
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    NSString *filename = [path lastPathComponent];

    // gather all the metadata needed for the mediaGroup
    NSString *titleStr = @"Upload Test";//[mTitleField stringValue];
    GDataMediaTitle *title = [GDataMediaTitle textConstructWithString:titleStr];

    NSString *categoryStr = @"Entertainment";//[[mCategoryPopup selectedItem] representedObject];
    GDataMediaCategory *category = [GDataMediaCategory mediaCategoryWithString:categoryStr];
    [category setScheme:kGDataSchemeYouTubeCategory];

    NSString *descStr = @"GData Description";//[mDescriptionField stringValue];
    GDataMediaDescription *desc = [GDataMediaDescription textConstructWithString:descStr];

    NSString *keywordsStr = @"RAGOpoR Demo";//[mKeywordsField stringValue];
    GDataMediaKeywords *keywords = [GDataMediaKeywords keywordsWithString:keywordsStr];

    BOOL isPrivate = NO;//([mPrivateCheckbox state] == NSOnState);

    GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
    [mediaGroup setMediaTitle:title];
    [mediaGroup setMediaDescription:desc];
    [mediaGroup addMediaCategory:category];
    [mediaGroup setMediaKeywords:keywords];
    [mediaGroup setIsPrivate:isPrivate];

    NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:path
                                               defaultMIMEType:@"video/mp4"];

    // create the upload entry with the mediaGroup and the file
    GDataEntryYouTubeUpload *entry;
    entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
                                                    fileHandle:fileHandle
                                                      MIMEType:mimeType
                                                          slug:filename];

    SEL progressSel = @selector(ticket:hasDeliveredByteCount:ofTotalByteCount:);
    [service setServiceUploadProgressSelector:progressSel];

    GDataServiceTicket *ticket;
    ticket = [service fetchEntryByInsertingEntry:entry
                                      forFeedURL:url
                                        delegate:self
                               didFinishSelector:@selector(uploadTicket:finishedWithEntry:error:)];
    [self setUploadTicket:ticket];
    GTMHTTPUploadFetcher *uploadFetcher = (GTMHTTPUploadFetcher *)[ticket objectFetcher];

}

Error EXC_BAD_ACCESS at

错误EXC_BAD_ACCESS在

NSString *path = [ExportoutputURL absoluteString];

5 个解决方案

#1


58  

Is it possible to convert NSUrl in to NSString for video file path.

是否可以将NSUrl转换为NSString用于视频文件路径。

Yes. Send it an absoluteString message.

是。发送一个absoluteString消息。

i have try to use NSString *path = [ExportoutputURL absoluteString]; but it crash.

我试着使用NSString * path = [ExportoutputURL absoluteString];但它崩溃了。

If you want a path, send the URL a path message. A string representing a URL is generally not a valid path; if you want a path, ask it for one.

如果需要路径,请向URL发送路径消息。表示URL的字符串通常不是有效路径;如果你想要一条路,请问一条路。

As for the crash, it does not mean absoluteString is wrong. Sending absoluteString to an NSURL object is the correct way to get an NSString object that represents the URL. The problem is somewhere else.

至于崩溃,它并不意味着absoluteString是错误的。将absoluteString发送到NSURL对象是获取表示URL的NSString对象的正确方法。问题出在其他地方。

Error EXC_BAD_ACCESS at

错误EXC_BAD_ACCESS在

NSString *path = [ExportoutputURL absoluteString];

This probably means that ExportoutputURL points to something that is not nil but is also not a valid object. It might have pointed to an NSURL object at some point, but it doesn't now.

这可能意味着ExportoutputURL指向不是nil但不是有效对象的东西。它可能在某个时刻指向了NSURL对象,但现在还没有。

My guess would be that the problem is this:

我的猜测是问题是这样的:

ExportoutputURL = session.outputURL;

You assign the URL to the ExportoutputURL instance variable, but you don't retain the object or make your own copy. Therefore, you don't own this object, which means you are not keeping it alive. It may die at any time, most probably after this method (exportDidFinish:) returns.

您将URL分配给ExportoutputURL实例变量,但您不保留该对象或制作您自己的副本。因此,您不拥有此对象,这意味着您不会保持它。它可能随时死亡,最有可能在此方法(exportDidFinish :)返回后死亡。

The crash is because you call uploadVideoFile later, after the URL object has already died. You still have a pointer to it, but that object no longer exists, so sending a message to it—any message—causes a crash.

崩溃是因为您在URL对象已经死亡之后稍后调用uploadVideoFile。你仍然有一个指向它的指针,但该对象不再存在,因此向它发送消息 - 任何消息 - 都会导致崩溃。

There are three simple solutions:

有三个简单的解决方案:

  1. Retain the URL object when you assign it to your instance variable.
  2. 将URL对象分配给实例变量时,请保留该URL对象。
  3. Make your own copy of the URL object and assign that to the instance variable.
  4. 制作您自己的URL对象副本,并将其分配给实例变量。
  5. Declare ExportoutputURL as a property, with either the strong keyword or the copy keyword, and assign the object to the property, not the instance variable. That will call the property's setter, which, if you synthesize it or implement it correctly, will retain or copy the URL for you.
  6. 使用strong关键字或copy关键字将ExportoutputURL声明为属性,并将对象分配给属性,而不是实例变量。这将调用属性的setter,如果你合成它或正确实现它,将保留或复制你的URL。

Either way, you will own the object, and that will keep it alive until you release it. Accordingly, you will need to release it when you are done with it (in dealloc, if not earlier), so that you don't leak it.

无论哪种方式,你将拥有该对象,这将使它保持活着直到你释放它。因此,您需要在完成它时(在dealloc中,如果不是更早的话)释放它,这样您就不会泄漏它。

This all assumes that you are not using ARC. If you are using Xcode 4.2 or later, and can require iOS 4 or later, you should migrate your project to ARC, as it makes so many things much simpler. You would not need to retain or copy this object if you were using ARC, which means that migrating to ARC now is a fourth solution (but certainly a larger-scale one).

这一切都假设您没有使用ARC。如果您使用的是Xcode 4.2或更高版本,并且可能需要iOS 4或更高版本,则应将项目迁移到ARC,因为它使许多事情变得更加简单。如果使用ARC,则不需要保留或复制此对象,这意味着现在迁移到ARC是第四种解决方案(但肯定是更大规模的解决方案)。

#2


11  

NSString *path = [[NSString alloc] initWithString:[url path]];  ?

#3


11  

Use either absolutePath or path as mentioned by Miek and Nepster. Expanding on their answers, the difference between lies in the prefix.

使用Miek和Nepster提到的absolutePath或path。扩展他们的答案,前缀之间的区别。

NSString* string1 = [url absoluteString]; // @"file:///Users/jackbrown/Music/song name.mp3"
NSString* string2 = [url path]; // @"/Users/jackbrown/Music/song name.mp3"`

#4


0  

Simply you can do it like this.

你可以这样做。

NSString *myString = [myURL absoluteString];

#5


0  

Use this. I think it will help you.

用这个。我认为它会对你有所帮助。

In Objective c

在目标c

NSString *testString = testUrl.absoluteString;

In Swift

在斯威夫特

var testString : String = testUrl.absoluteString

#1


58  

Is it possible to convert NSUrl in to NSString for video file path.

是否可以将NSUrl转换为NSString用于视频文件路径。

Yes. Send it an absoluteString message.

是。发送一个absoluteString消息。

i have try to use NSString *path = [ExportoutputURL absoluteString]; but it crash.

我试着使用NSString * path = [ExportoutputURL absoluteString];但它崩溃了。

If you want a path, send the URL a path message. A string representing a URL is generally not a valid path; if you want a path, ask it for one.

如果需要路径,请向URL发送路径消息。表示URL的字符串通常不是有效路径;如果你想要一条路,请问一条路。

As for the crash, it does not mean absoluteString is wrong. Sending absoluteString to an NSURL object is the correct way to get an NSString object that represents the URL. The problem is somewhere else.

至于崩溃,它并不意味着absoluteString是错误的。将absoluteString发送到NSURL对象是获取表示URL的NSString对象的正确方法。问题出在其他地方。

Error EXC_BAD_ACCESS at

错误EXC_BAD_ACCESS在

NSString *path = [ExportoutputURL absoluteString];

This probably means that ExportoutputURL points to something that is not nil but is also not a valid object. It might have pointed to an NSURL object at some point, but it doesn't now.

这可能意味着ExportoutputURL指向不是nil但不是有效对象的东西。它可能在某个时刻指向了NSURL对象,但现在还没有。

My guess would be that the problem is this:

我的猜测是问题是这样的:

ExportoutputURL = session.outputURL;

You assign the URL to the ExportoutputURL instance variable, but you don't retain the object or make your own copy. Therefore, you don't own this object, which means you are not keeping it alive. It may die at any time, most probably after this method (exportDidFinish:) returns.

您将URL分配给ExportoutputURL实例变量,但您不保留该对象或制作您自己的副本。因此,您不拥有此对象,这意味着您不会保持它。它可能随时死亡,最有可能在此方法(exportDidFinish :)返回后死亡。

The crash is because you call uploadVideoFile later, after the URL object has already died. You still have a pointer to it, but that object no longer exists, so sending a message to it—any message—causes a crash.

崩溃是因为您在URL对象已经死亡之后稍后调用uploadVideoFile。你仍然有一个指向它的指针,但该对象不再存在,因此向它发送消息 - 任何消息 - 都会导致崩溃。

There are three simple solutions:

有三个简单的解决方案:

  1. Retain the URL object when you assign it to your instance variable.
  2. 将URL对象分配给实例变量时,请保留该URL对象。
  3. Make your own copy of the URL object and assign that to the instance variable.
  4. 制作您自己的URL对象副本,并将其分配给实例变量。
  5. Declare ExportoutputURL as a property, with either the strong keyword or the copy keyword, and assign the object to the property, not the instance variable. That will call the property's setter, which, if you synthesize it or implement it correctly, will retain or copy the URL for you.
  6. 使用strong关键字或copy关键字将ExportoutputURL声明为属性,并将对象分配给属性,而不是实例变量。这将调用属性的setter,如果你合成它或正确实现它,将保留或复制你的URL。

Either way, you will own the object, and that will keep it alive until you release it. Accordingly, you will need to release it when you are done with it (in dealloc, if not earlier), so that you don't leak it.

无论哪种方式,你将拥有该对象,这将使它保持活着直到你释放它。因此,您需要在完成它时(在dealloc中,如果不是更早的话)释放它,这样您就不会泄漏它。

This all assumes that you are not using ARC. If you are using Xcode 4.2 or later, and can require iOS 4 or later, you should migrate your project to ARC, as it makes so many things much simpler. You would not need to retain or copy this object if you were using ARC, which means that migrating to ARC now is a fourth solution (but certainly a larger-scale one).

这一切都假设您没有使用ARC。如果您使用的是Xcode 4.2或更高版本,并且可能需要iOS 4或更高版本,则应将项目迁移到ARC,因为它使许多事情变得更加简单。如果使用ARC,则不需要保留或复制此对象,这意味着现在迁移到ARC是第四种解决方案(但肯定是更大规模的解决方案)。

#2


11  

NSString *path = [[NSString alloc] initWithString:[url path]];  ?

#3


11  

Use either absolutePath or path as mentioned by Miek and Nepster. Expanding on their answers, the difference between lies in the prefix.

使用Miek和Nepster提到的absolutePath或path。扩展他们的答案,前缀之间的区别。

NSString* string1 = [url absoluteString]; // @"file:///Users/jackbrown/Music/song name.mp3"
NSString* string2 = [url path]; // @"/Users/jackbrown/Music/song name.mp3"`

#4


0  

Simply you can do it like this.

你可以这样做。

NSString *myString = [myURL absoluteString];

#5


0  

Use this. I think it will help you.

用这个。我认为它会对你有所帮助。

In Objective c

在目标c

NSString *testString = testUrl.absoluteString;

In Swift

在斯威夫特

var testString : String = testUrl.absoluteString